package jnpf.engine.util;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import jnpf.base.UserInfo;
import jnpf.constant.MsgCode;
import jnpf.database.model.dto.PrepareSqlDTO;
import jnpf.database.model.entity.DbLinkEntity;
import jnpf.database.util.JdbcUtil;
import jnpf.engine.entity.*;
import jnpf.engine.enums.*;
import jnpf.engine.model.DataModel;
import jnpf.engine.model.flowengine.FlowModel;
import jnpf.engine.model.flowengine.FlowOperator;
import jnpf.engine.model.flowengine.FlowOperatordModel;
import jnpf.engine.model.flowengine.FlowUpdateNode;
import jnpf.engine.model.flowengine.shuntjson.childnode.ChildNode;
import jnpf.engine.model.flowengine.shuntjson.childnode.FlowAssignModel;
import jnpf.engine.model.flowengine.shuntjson.childnode.Properties;
import jnpf.engine.model.flowengine.shuntjson.nodejson.ChildNodeList;
import jnpf.engine.model.flowengine.shuntjson.nodejson.ConditionList;
import jnpf.engine.model.flowengine.shuntjson.nodejson.Custom;
import jnpf.engine.model.flowengine.shuntjson.nodejson.DateProperties;
import jnpf.engine.model.flowmessage.FlowMsgModel;
import jnpf.engine.model.flowtask.*;
import jnpf.engine.model.flowtask.method.TaskChild;
import jnpf.engine.model.flowtask.method.TaskHandleIdStatus;
import jnpf.engine.model.flowtask.method.TaskOperatoUser;
import jnpf.engine.model.flowtask.method.TaskOperator;
import jnpf.engine.service.*;
import jnpf.exception.WorkFlowException;
import jnpf.model.FormAllModel;
import jnpf.model.FormEnum;
import jnpf.model.visiual.*;
import jnpf.model.visiual.fields.FieLdsModel;
import jnpf.permission.constant.PermissionConst;
import jnpf.permission.entity.OrganizeEntity;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.entity.UserRelationEntity;
import jnpf.permission.model.permission.PermissionModel;
import jnpf.util.*;
import jnpf.util.context.SpringContext;
import jnpf.util.wxutil.HttpUtil;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ：JNPF开发平台组
 * @version: V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date ：2022/6/15 13:54
 */
@Component
@Slf4j
public class FlowTaskUtil {

    /**
     * 节点id
     **/
    public String taskNodeId = "taskNodeId";
    /**
     * 任务id
     **/
    public String taskId = "taskId";
    /**
     * 空节点默认审批人
     **/
    public String user = "admin";

    @Autowired
    public FlowDataUtil flowDataUtil;
    @Autowired
    public FlowUserService flowUserService;
    @Autowired
    public FlowCandidatesService flowCandidatesService;
    @Autowired
    public FlowTaskNodeService flowTaskNodeService;
    @Autowired
    public FlowTaskOperatorService flowTaskOperatorService;
    @Autowired
    public FlowTaskOperatorRecordService flowTaskOperatorRecordService;
    @Autowired
    public FlowMsgUtil flowMsgUtil;
    @Autowired
    public FlowEngineService flowEngineService;
    @Autowired
    public FlowTaskService flowTaskService;
    @Autowired
    public FlowTaskNewService flowTaskNewService;
    @Autowired
    public ServiceAllUtil serviceUtil;
    @Autowired
    private FlowOperatorUserService flowOperatorUserService;


    //--------------------------------------候选人------------------------------------------------------------------

    /**
     * 查询候选人
     *
     * @param taskNodeList     所有节点
     * @param childNodeListAll 节点数据
     * @param nodeCode         当前节点
     */
    public void candidate(List<FlowTaskNodeEntity> taskNodeList, List<ChildNodeList> childNodeListAll, String nodeCode, boolean isNext) {
        List<FlowTaskNodeEntity> nodeList = taskNodeList.stream().filter(t -> t.getNodeCode().equals(nodeCode)).collect(Collectors.toList());
        for (FlowTaskNodeEntity taskNodeEntity : nodeList) {
            if (isNext) {
                List<String> nextNodeList = Arrays.asList(taskNodeEntity.getNodeNext().split(","));
                List<FlowTaskNodeEntity> nextTaskNodeList = taskNodeList.stream().filter(t -> nextNodeList.contains(t.getNodeCode())).collect(Collectors.toList());
                for (FlowTaskNodeEntity nodeEntity : nextTaskNodeList) {
                    String nodeType = nodeEntity.getNodeType();
                    String code = nodeEntity.getNodeCode();
                    if (FlowNature.NodeSubFlow.equals(nodeType)) {
                        this.candidate(taskNodeList, childNodeListAll, code, isNext);
                    } else {
                        ChildNodeList taskNode = JsonUtil.getJsonToBean(taskNodeEntity.getNodePropertyJson(), ChildNodeList.class);
                        ChildNodeList childNodeList = JsonUtil.getJsonToBean(nodeEntity.getNodePropertyJson(), ChildNodeList.class);
                        childNodeList.getCustom().setBranchFlow(taskNode.getCustom().getBranchFlow());
                        childNodeList.getCustom().setFlow(taskNode.getCustom().getFlow());
                        childNodeListAll.add(childNodeList);
                    }
                }
            } else {
                ChildNodeList childNodeList = JsonUtil.getJsonToBean(taskNodeEntity.getNodePropertyJson(), ChildNodeList.class);
                childNodeListAll.add(childNodeList);
            }
        }
    }

    //-----------------------------------提交保存--------------------------------------------

    /**
     * 获取节点候选人
     *
     * @param operatorEntity
     * @return
     * @throws WorkFlowException
     */
    public List<ChildNodeList> childNodeListAll(FlowTaskOperatorEntity operatorEntity, FlowModel flowModel) throws WorkFlowException {
        List<ChildNodeList> childNodeListAll = new ArrayList<>();
        List<FlowTaskNodeEntity> taskNodeList = new ArrayList<>();
        List<ConditionList> conditionListAll = new ArrayList<>();
        String startNode = "";
        UserInfo userInfo = flowModel.getUserInfo();
        boolean isNodeCode = StringUtil.isNotEmpty(flowModel.getNodeCode());
        boolean operator = operatorEntity != null;
        Map<String, Object> formData = flowModel.getFormData();
        Object flowId = formData.get("flowId");
        if (ObjectUtil.isNotNull(flowId)) {
            FlowEngineEntity engine = flowEngineService.getInfo(String.valueOf(flowId));
            if (FlowNature.CUSTOM.equals(engine.getFormType())) {
                Map<String, Object> formDataAll = flowModel.getFormData();
                Object data = formDataAll.get("data");
                if (data != null) {
                    formData = JsonUtil.stringToMap(String.valueOf(data));
                }
            }
            ChildNode childNodeAll = JsonUtil.getJsonToBean(engine.getFlowTemplateJson(), ChildNode.class);
            //获取流程节点
            List<ChildNodeList> nodeListAll = new ArrayList<>();
            //递归获取条件数据和节点数据
            FlowTaskEntity flowTask = new FlowTaskEntity();
            if (operator) {
                flowTask = flowTaskService.getInfo(operatorEntity.getTaskId());
            } else {
                flowTask.setId(RandomUtil.uuId());
                flowTask.setCreatorUserId(userInfo.getUserId());
                flowTask.setCreatorTime(new Date());
            }
            flowTask.setFlowFormContentJson(JsonUtil.getObjectToString(formData));
            FlowUpdateNode updateNode = FlowUpdateNode.builder().childNodeAll(childNodeAll).nodeListAll(nodeListAll).taskNodeList(taskNodeList).conditionListAll(conditionListAll).flowTask(flowTask).userInfo(userInfo).isSubmit(!operator).build();
            this.updateNodeList(updateNode);
            Optional<FlowTaskNodeEntity> first = taskNodeList.stream().filter(t -> FlowNature.NodeStart.equals(t.getNodeType())).findFirst();
            if (!first.isPresent()) {
                throw new WorkFlowException(MsgCode.COD001.get());
            }
            FlowTaskNodeEntity startNodes = first.get();
            startNode = startNodes.getNodeCode();
            this.nodeList(taskNodeList, startNode, 1L);
        }
        String nodeCode = isNodeCode ? flowModel.getNodeCode() : operator ? operatorEntity.getNodeCode() : startNode;
        //判断条件下选择分支
        FlowTaskNodeEntity taskNode = taskNodeList.stream().filter(t -> t.getNodeCode().equals(nodeCode)).findFirst().orElse(null);
        if (taskNode != null) {
            for (ConditionList condition : conditionListAll) {
                if (taskNode.getNodeNext().equals(condition.getFlowId())) {
                    ChildNodeList childNodeList = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
                    childNodeList.getCustom().setBranchFlow(condition.getBranchFlow());
                    taskNode.setNodePropertyJson(JsonUtil.getObjectToString(childNodeList));
                }
            }
        }
        this.candidate(taskNodeList, childNodeListAll, nodeCode, !isNodeCode);
        return childNodeListAll;
    }

    /**
     * 流程任务赋值
     *
     * @param taskEntity 流程任务实例
     * @param engine     流程引擎实例
     * @param flowModel  提交数据
     * @throws WorkFlowException 异常
     */
    public void task(FlowTaskEntity taskEntity, FlowEngineEntity engine, FlowModel flowModel, String userId) throws WorkFlowException {
        if (flowModel.getId() != null && !checkStatus(taskEntity.getStatus())) {
            throw new WorkFlowException(MsgCode.WF108.get());
        }
        //创建实例
        taskEntity.setId(flowModel.getProcessId());
        taskEntity.setProcessId(flowModel.getProcessId());
        taskEntity.setEnCode(flowModel.getBillNo());
        taskEntity.setFullName(flowModel.getFlowTitle());
        taskEntity.setFlowUrgent(flowModel.getFlowUrgent() != null ? flowModel.getFlowUrgent() : 1);
        taskEntity.setFlowId(engine.getId());
        taskEntity.setFlowCode(engine.getEnCode() != null ? engine.getEnCode() : MsgCode.WF109.get());
        taskEntity.setFlowName(engine.getFullName());
        taskEntity.setFlowType(engine.getType());
        taskEntity.setFlowCategory(engine.getCategory());
        taskEntity.setFlowForm(engine.getFormData());
        taskEntity.setFlowTemplateJson(engine.getFlowTemplateJson());
        taskEntity.setFlowVersion(engine.getVersion());
        taskEntity.setStatus(FlowStatusEnum.save.getMessage().equals(flowModel.getStatus()) ? FlowTaskStatusEnum.Draft.getCode() : FlowTaskStatusEnum.Handle.getCode());
        taskEntity.setCompletion(FlowNature.ProcessCompletion);
        taskEntity.setCreatorTime(new Date());
        taskEntity.setEnabledMark(1);
        taskEntity.setFormType(engine.getFormType());
        taskEntity.setCreatorUserId(userId);
        taskEntity.setFlowFormContentJson(flowModel.getFormData() != null ? JsonUtil.getObjectToString(flowModel.getFormData()) : "{}");
        taskEntity.setParentId(flowModel.getParentId() != null ? flowModel.getParentId() : FlowNature.ParentId);
        taskEntity.setIsAsync(flowModel.getIsAsync() ? FlowNature.ChildAsync : FlowNature.ChildSync);
        ChildNode childNode = JsonUtil.getJsonToBean(engine.getFlowTemplateJson(), ChildNode.class);
        boolean isBatchApproval = false;
        if (ObjectUtil.isNotEmpty(childNode.getProperties().getIsBatchApproval()) && childNode.getProperties().getIsBatchApproval()) {
            isBatchApproval = true;
        }
        taskEntity.setIsBatch(isBatchApproval ? 1 : 0);
    }

    /**
     * 验证有效状态
     *
     * @param status 状态编码
     * @return
     */
    public boolean checkStatus(int status) {
        if (status == FlowTaskStatusEnum.Draft.getCode() || status == FlowTaskStatusEnum.Reject.getCode() || status == FlowTaskStatusEnum.Revoke.getCode()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 提交节点
     *
     * @param nodeListModel 条件对象
     */
    public void nodeListAll(FlowNodeListModel nodeListModel) {
        List<FlowTaskNodeEntity> dataAll = nodeListModel.getDataAll();
        FlowModel flowModel = nodeListModel.getFlowModel();
        boolean isAdd = nodeListModel.getIsAdd();
        FlowTaskNodeEntity taskNode = nodeListModel.getTaskNode();
        long num = nodeListModel.getNum();
        UserInfo userInfo = flowModel.getUserInfo();
        this.nodeList(dataAll, taskNode.getNodeCode(), num);
        String nodeNext = FlowNature.NodeEnd;
        String type = FlowNature.EndRound;
        long maxNum = 99L;
        Map<String, List<String>> candidateList = flowModel.getCandidateList() != null ? flowModel.getCandidateList() : new HashMap<>();
        Map<String, List<String>> candidateErrorList = flowModel.getErrorRuleUserList() != null ? flowModel.getErrorRuleUserList() : new HashMap<>();
        List<FlowCandidatesEntity> candidateListAll = new ArrayList<>();
        for (int i = 0; i < dataAll.size(); i++) {
            FlowTaskNodeEntity entity = dataAll.get(i);
            if (StringUtil.isEmpty(entity.getNodeNext())) {
                entity.setNodeNext(nodeNext);
            }
            if (!"timer".equals(entity.getNodeType())) {
                //候选人
                List<String> list = candidateList.get(entity.getNodeCode()) != null ? candidateList.get(entity.getNodeCode()) : new ArrayList<>();
                if (list.size() > 0) {
                    FlowCandidatesEntity candidates = new FlowCandidatesEntity();
                    candidates.setHandleId(userInfo.getUserId());
                    candidates.setTaskNodeId(entity.getId());
                    candidates.setTaskId(entity.getTaskId());
                    candidates.setAccount(userInfo.getUserAccount());
                    candidates.setCandidates(JsonUtil.getObjectToString(list));
                    candidates.setOperatorId(FlowNature.ParentId);
                    candidates.setType(FlowNature.Candidates);
                    candidateListAll.add(candidates);
                }
                //异常人
                List<String> errorList = candidateErrorList.get(entity.getNodeCode()) != null ? candidateErrorList.get(entity.getNodeCode()) : new ArrayList<>();
                if (errorList.size() > 0) {
                    FlowCandidatesEntity candidates = new FlowCandidatesEntity();
                    candidates.setHandleId(userInfo.getUserId());
                    candidates.setTaskNodeId(entity.getId());
                    candidates.setTaskId(entity.getTaskId());
                    candidates.setAccount(userInfo.getUserAccount());
                    candidates.setCandidates(JsonUtil.getObjectToString(errorList));
                    candidates.setOperatorId(FlowNature.ParentId);
                    candidates.setType(FlowNature.CandidatesError);
                    candidateListAll.add(candidates);
                }
                //选择分支
                List<String> branchList = flowModel.getBranchList() != null ? flowModel.getBranchList() : new ArrayList<>();
                List<String> flowIdList = new ArrayList() {{
                    add(entity.getNodeCode());
                }};
                flowIdList.retainAll(branchList);
                entity.setCandidates(flowIdList.size() > 0 ? JsonUtil.getObjectToString(branchList) : JsonUtil.getObjectToString(new ArrayList<>()));
            } else {
                dataAll.remove(i);
                i--;
            }
        }
        if (isAdd) {
            FlowTaskNodeEntity endround = new FlowTaskNodeEntity();
            endround.setId(RandomUtil.uuId());
            endround.setNodeCode(nodeNext);
            endround.setNodeName(MsgCode.WF007.get());
            endround.setCompletion(FlowNature.ProcessCompletion);
            endround.setCreatorTime(new Date());
            endround.setSortCode(maxNum);
            endround.setTaskId(taskNode.getTaskId());
            ChildNodeList endNode = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
            endNode.getCustom().setNodeId(nodeNext);
            endNode.setTaskNodeId(endround.getId());
            endNode.getCustom().setType(type);
            endround.setNodePropertyJson(JsonUtil.getObjectToString(endNode));
            endround.setNodeType(type);
            endround.setState(FlowNodeEnum.Process.getCode());
            endround.setNodeNext("");
            dataAll.add(endround);
            for (FlowTaskNodeEntity entity : dataAll) {
                flowTaskNodeService.create(entity);
            }
            for (FlowCandidatesEntity entity : candidateListAll) {
                flowCandidatesService.create(entity);
            }
        }
    }

    /**
     * 递归遍历编码
     *
     * @param dataAll 所有节点
     * @param node    当前节点
     * @param num     排序
     */
    public void nodeList(List<FlowTaskNodeEntity> dataAll, String node, long num) {
        List<String> nodeAll = Arrays.asList(node.split(","));
        List<FlowTaskNodeEntity> nodeList = dataAll.stream().filter(t -> nodeAll.contains(t.getNodeCode())).collect(Collectors.toList());
        for (FlowTaskNodeEntity entity : nodeList) {
            entity.setSortCode(num);
            entity.setState(FlowNodeEnum.Process.getCode());
        }
        List<String> nextNode = nodeList.stream().filter(t -> StringUtil.isNotEmpty(t.getNodeNext())).map(FlowTaskNodeEntity::getNodeNext).collect(Collectors.toList());
        if (nextNode.size() > 0) {
            String nodes = String.join(",", nextNode);
            num++;
            nodeList(dataAll, nodes, num);
        }
    }

    /**
     * 流程用户信息
     *
     * @param flowTask
     */
    public void flowUser(FlowTaskEntity flowTask) {
        UserEntity user = serviceUtil.getUserInfo(flowTask.getCreatorUserId());
        FlowUserEntity flowUser = new FlowUserEntity();
        flowUser.setTaskId(flowTask.getId());
        if (user != null) {
            flowUser.setManagerId(user.getManagerId());
            flowUser.setOrganizeId(user.getOrganizeId());
            flowUser.setPositionId(user.getPositionId());
            String listByManagerId = serviceUtil.getListByManagerId(user.getId()).stream().map(UserEntity::getId).collect(Collectors.joining(","));
            flowUser.setSubordinate(listByManagerId);
            flowUser.setSuperior(user.getManagerId());
            List<OrganizeEntity> departmentAll = serviceUtil.getDepartmentAll(user.getOrganizeId());
            String department = departmentAll.stream().map(OrganizeEntity::getId).collect(Collectors.joining(","));
            flowUser.setDepartment(department);

        }
        flowUserService.create(flowUser);
    }

    //-------------------------审批--------------------------------
    //---------通过-------------

    /**
     * 修改选择分支的流程状态
     *
     * @param nodeCodeList
     * @param taskNodeList
     * @param operatorList
     */
    public void branchTaskNode(List<String> nodeCodeList, List<FlowTaskNodeEntity> taskNodeList, List<FlowTaskOperatorEntity> operatorList) {
        if (operatorList.size() > 0) {
            Set<String> operatorNode = operatorList.stream().map(FlowTaskOperatorEntity::getNodeCode).collect(Collectors.toSet());
            if (operatorNode.size() != nodeCodeList.size()) {
                //差集
                List<String> reduce = nodeCodeList.stream().filter(item -> !operatorNode.contains(item)).collect(Collectors.toList());
                List<String> reduceList = taskNodeList.stream().filter(t -> reduce.contains(t.getNodeCode())).map(FlowTaskNodeEntity::getId).collect(Collectors.toList());
                Set<String> reduceListAll = new HashSet<>();
                this.upAll(reduceListAll, reduceList, taskNodeList);
                flowTaskNodeService.updateCompletion(new ArrayList<>(reduceListAll), FlowNature.AuditCompletion);
                //交集
                List<String> intersec = nodeCodeList.stream().filter(item -> operatorNode.contains(item)).collect(Collectors.toList());
                List<String> intersecList = taskNodeList.stream().filter(t -> intersec.contains(t.getNodeCode())).map(FlowTaskNodeEntity::getId).collect(Collectors.toList());
                Set<String> intersectionList = new HashSet<>();
                this.upAll(intersectionList, intersecList, taskNodeList);
                flowTaskNodeService.updateCompletion(new ArrayList<>(intersectionList), FlowNature.ProcessCompletion);
            }
        }
    }

    /**
     * 修改系统表单数据
     *
     * @param code 编码
     * @param id   主键id
     * @param data 数据
     * @throws WorkFlowException
     */
    public void formData(String code, String id, String data) throws WorkFlowException {
        Map<String, Object> objectData = JsonUtil.stringToMap(data);
        if (objectData.size() > 0) {
            try {
                Class[] types = new Class[]{String.class, String.class};
                Object[] datas = new Object[]{id, data};
                Object service = SpringContext.getBean(code + "ServiceImpl");
                ReflectionUtil.invokeMethod(service, "data", types, datas);
            } catch (Exception e) {
                log.error(MsgCode.WF119.get() + ":{}", e.getMessage());
                throw new WorkFlowException(MsgCode.WF119.get());
            }
        }
    }

    /**
     * 创建节点
     *
     * @param flowTask
     * @param nodeListAll
     * @param conditionListAll
     * @param taskNodeList
     */
    public void createNodeList(FlowTaskEntity flowTask, List<ChildNodeList> nodeListAll, List<ConditionList> conditionListAll, List<FlowTaskNodeEntity> taskNodeList, UserInfo userInfo, boolean isSubmit) {
        List<FlowTaskNodeEntity> timerList = new ArrayList<>();
        List<FlowTaskNodeEntity> emptyList = new ArrayList<>();
        UserEntity userEntity = serviceUtil.getUserInfo(flowTask.getCreatorUserId());
        if (!isSubmit) {
            flowTask.setLastModifyUserId(userInfo.getUserId());
            flowTask.setLastModifyTime(new Date());
        }
        for (ChildNodeList childNode : nodeListAll) {
            FlowTaskNodeEntity taskNode = new FlowTaskNodeEntity();
            String nodeId = childNode.getCustom().getNodeId();
            Properties properties = childNode.getProperties();
            String dataJson = flowTask.getFlowFormContentJson();
            String type = childNode.getCustom().getType();
            taskNode.setId(RandomUtil.uuId());
            childNode.setTaskNodeId(taskNode.getId());
            childNode.setTaskId(flowTask.getId());
            taskNode.setCreatorTime(new Date());
            taskNode.setTaskId(flowTask.getId());
            taskNode.setNodeCode(nodeId);
            taskNode.setNodeType(type);
            taskNode.setState(FlowNodeEnum.Futility.getCode());
            taskNode.setSortCode(-2L);
            taskNode.setNodeUp(properties.getRejectStep());
            FlowConditionModel conditionModel = FlowConditionModel.builder().conditionListAll(conditionListAll).childNodeListAll(nodeListAll).flowTaskEntity(flowTask).data(dataJson).nodeId(nodeId).build();
            conditionModel.setUserEntity(userEntity);
            conditionModel.setFlowTaskEntity(flowTask);
            conditionModel.setUserInfo(userInfo);
            taskNode.setNodeNext(FlowJsonUtil.getNextNode(conditionModel));
            //赋值分支属性
            ConditionList conditionList = conditionListAll.stream().filter(t -> taskNode.getNodeNext().equals(t.getFlowId())).findFirst().orElse(null);
            if (conditionList != null) {
                childNode.getCustom().setFlow(conditionList.getFlow());
                childNode.getCustom().setBranchFlow(conditionList.getBranchFlow());
                childNode.getCustom().setFlowId(conditionList.getFlowId());
            }
            taskNode.setNodePropertyJson(JsonUtil.getObjectToString(childNode));
            boolean isStart = FlowNature.NodeStart.equals(childNode.getCustom().getType());
            taskNode.setCompletion(isStart ? FlowNature.AuditCompletion : FlowNature.ProcessCompletion);
            taskNode.setNodeName(isStart ? MsgCode.WF006.get() : properties.getTitle());
            taskNodeList.add(taskNode);
            if ("empty".equals(type)) {
                emptyList.add(taskNode);
            }
            if ("timer".equals(type)) {
                timerList.add(taskNode);
            }
        }
        //指向empty，继续指向下一个节点
        for (FlowTaskNodeEntity empty : emptyList) {
            List<FlowTaskNodeEntity> noxtEmptyList = taskNodeList.stream().filter(t -> t.getNodeNext().contains(empty.getNodeCode())).collect(Collectors.toList());
            for (FlowTaskNodeEntity entity : noxtEmptyList) {
                entity.setNodeNext(empty.getNodeNext());
            }
        }
        //指向timer，继续指向下一个节点
        for (FlowTaskNodeEntity timer : timerList) {
            //获取到timer的上一节点
            ChildNodeList timerlList = JsonUtil.getJsonToBean(timer.getNodePropertyJson(), ChildNodeList.class);
            DateProperties timers = timerlList.getTimer();
            timers.setNodeId(timer.getNodeCode());
            timers.setTime(true);
            List<FlowTaskNodeEntity> upEmptyList = taskNodeList.stream().filter(t -> t.getNodeNext().contains(timer.getNodeCode())).collect(Collectors.toList());
            for (FlowTaskNodeEntity entity : upEmptyList) {
                //上一节点赋值timer的属性
                ChildNodeList modelList = JsonUtil.getJsonToBean(entity.getNodePropertyJson(), ChildNodeList.class);
                modelList.setTimer(timers);
                entity.setNodeNext(timer.getNodeNext());
                entity.setNodePropertyJson(JsonUtil.getObjectToString(modelList));
            }
        }
    }

    /**
     * 判断是否进行下一步
     *
     * @param nodeListAll    所有节点
     * @param nextNodeEntity 下一节点
     * @param taskNode       当前节点
     * @param flowModel      提交数据
     * @return
     */
    public List<FlowTaskNodeEntity> isNextAll(List<FlowTaskNodeEntity> nodeListAll, List<FlowTaskNodeEntity> nextNodeEntity, FlowTaskNodeEntity taskNode, FlowModel flowModel) {
        //1.先看是否加签人，有都不要进行，无进行下一步
        //2.判断会签是否比例通过
        //3.判断分流是否都结束
        //4.判断审批人是否都通过
        List<FlowTaskNodeEntity> result = new ArrayList<>();
        boolean hasFreeApprover = StringUtil.isNotEmpty(flowModel.getFreeApproverUserId());
        if (hasFreeApprover) {
            result.add(taskNode);
            //加签记录
        } else {
            //会签通过
            List<FlowTaskOperatorEntity> operatorList = flowTaskOperatorService.getList(taskNode.getTaskId()).stream().filter(t -> t.getTaskNodeId().equals(taskNode.getId()) && FlowNodeEnum.Process.getCode().equals(t.getState())).collect(Collectors.toList());
            FlowCountersignModel countersign = new FlowCountersignModel();
            countersign.setTaskNodeId(taskNode.getId());
            countersign.setOperatorList(operatorList);
            //判断是否是会签
            boolean isCountersign = this.isCountersign(countersign);
            ChildNodeList nodeModel = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
            Properties properties = nodeModel.getProperties();
            String type = properties.getAssigneeType();
            //流程通过
            if (isCountersign) {
                flowTaskOperatorService.update(nodeModel.getTaskNodeId(), type);
                taskNode.setCompletion(FlowNature.AuditCompletion);
                taskNode.setDraftData(JsonUtil.getObjectToString(flowModel.getFormData()));
                //跟新审批状态
                flowTaskNodeService.update(taskNode);
                //分流通过
                boolean isShunt = this.isShunt(nodeListAll, nextNodeEntity, taskNode);
                if (isShunt) {
                    result.addAll(nextNodeEntity);
                }
            }
        }
        return result;
    }

    /**
     * 判断会签比例
     *
     * @param operatorList
     * @return
     */
    public boolean fixedJointly(List<FlowTaskOperatorEntity> operatorList, ChildNodeList nodeModel, FlowCountersignModel countersign) {
        Properties properties = nodeModel.getProperties();
        boolean isCountersign = true;
        boolean fixed = !FlowNature.FixedApprover.equals(properties.getCounterSign());
        long pass = properties.getCountersignRatio();
        countersign.setFixed(fixed);
        countersign.setPass(pass);
        if (fixed) {
            double total = operatorList.stream().filter(t -> FlowNature.ParentId.equals(t.getParentId())).count();
            List<FlowTaskOperatorEntity> passNumList = this.passNum(operatorList, FlowNature.AuditCompletion);
            countersign.setPassNumList(passNumList);
            double passNum = passNumList.size();
            isCountersign = this.isCountersign(pass, total, passNum);
        }
        return isCountersign;
    }

    /**
     * 判断分流是否结束
     *
     * @param nodeListAll    所有节点
     * @param nextNodeEntity 下一节点
     * @param taskNode       单前节点
     * @return
     */
    public boolean isShunt(List<FlowTaskNodeEntity> nodeListAll, List<FlowTaskNodeEntity> nextNodeEntity, FlowTaskNodeEntity taskNode) {
        boolean isNext = true;
        for (FlowTaskNodeEntity nodeEntity : nextNodeEntity) {
            String nextNode = nodeEntity.getNodeCode();
            List<FlowTaskNodeEntity> interflowAll = nodeListAll.stream().filter(t -> String.valueOf(t.getNodeNext()).contains(nextNode) && FlowNodeEnum.Process.getCode().equals(t.getState())).collect(Collectors.toList());
            List<FlowTaskNodeEntity> flowAll = interflowAll.stream().filter(t -> !FlowNature.AuditCompletion.equals(t.getCompletion())).collect(Collectors.toList());
            if (flowAll.size() > 0) {
                isNext = false;
                break;
            }
        }
        return isNext;
    }

    /**
     * 修改节点走向
     */
    public void auditTaskNode(FlowEngineEntity engine, FlowTaskEntity flowTask, FlowTaskOperatorEntity operator, FlowModel flowModel) {
        UserInfo userInfo = flowModel.getUserInfo();
        List<Integer> completion = new ArrayList() {{
            add(FlowNodeEnum.Process.getCode());
        }};
        List<FlowTaskNodeEntity> flowTaskNodeListAll = flowTaskNodeService.getList(flowTask.getId()).stream().filter(t -> completion.contains(t.getCompletion()) && !FlowNature.NodeEnd.equals(t.getNodeCode())).collect(Collectors.toList());
        //更新数据
        flowModel.setProcessId(flowTask.getId());
        flowModel.setId(flowTask.getId());
        Map<String, Object> dataAll = JsonUtil.stringToMap(flowTask.getFlowFormContentJson());
        if (FlowNature.CUSTOM.equals(engine.getFormType())) {
            Map<String, Object> formDataAll = flowModel.getFormData();
            Object datas = formDataAll.get("data");
            flowModel.setFormData(dataAll);
            if (datas != null) {
                Map<String, Object> data = JsonUtil.stringToMap(String.valueOf(datas));
                flowModel.setFormData(data);
            }
        }
        //更新新流程
        ChildNode childNodeAll = JsonUtil.getJsonToBean(flowTask.getFlowTemplateJson(), ChildNode.class);
        List<ChildNodeList> nodeListAll = new ArrayList<>();
        List<ConditionList> conditionListAll = new ArrayList<>();
        List<FlowTaskNodeEntity> taskNodeLisAll = new ArrayList<>();
        flowTask.setFlowFormContentJson(JsonUtil.getObjectToString(flowModel.getFormData()));
        FlowUpdateNode updateNode = FlowUpdateNode.builder().childNodeAll(childNodeAll).nodeListAll(nodeListAll).taskNodeList(taskNodeLisAll).conditionListAll(conditionListAll).flowTask(flowTask).userInfo(userInfo).build();
        this.updateNodeList(updateNode);
        FlowTaskNodeEntity flowTaskNode = flowTaskNodeListAll.stream().filter(t -> t.getId().equals(operator.getTaskNodeId())).findFirst().orElse(null);
        if (flowTaskNode != null) {
            FlowNodeListModel nodeListModel = new FlowNodeListModel(taskNodeLisAll, flowModel, false, flowTaskNode, flowTaskNode.getSortCode());
            this.nodeListAll(nodeListModel);
        }
        //修改节点的id
        taskNodeLisAll.stream().forEach(k -> {
            FlowTaskNodeEntity taskNodeEntity = flowTaskNodeListAll.stream().filter(t -> t.getNodeCode().equals(k.getNodeCode())).findFirst().orElse(null);
            if (taskNodeEntity != null) {
                k.setId(taskNodeEntity.getId());
            }
        });
        //递归新节点
        Set<String> rejectNodeList = new HashSet<>();
        List<String> rejectList = new ArrayList() {{
            add(operator.getTaskNodeId());
        }};
        this.upAll(rejectNodeList, rejectList, taskNodeLisAll);
        //递归旧节点
        this.upAll(rejectNodeList, rejectList, flowTaskNodeListAll);
        //更新没有走过的节点状态
        List<String> branchList = flowModel.getBranchList() != null ? flowModel.getBranchList() : new ArrayList<>();
        List<FlowTaskNodeEntity> flowTaskNodeList = flowTaskNodeListAll.stream().filter(t -> rejectNodeList.contains(t.getId())).collect(Collectors.toList());
        for (FlowTaskNodeEntity taskNode : flowTaskNodeList) {
            FlowTaskNodeEntity nodeEntity = taskNodeLisAll.stream().filter(t -> t.getNodeCode().equals(taskNode.getNodeCode())).findFirst().orElse(null);
            List<String> candidatesList = branchList.contains(taskNode.getNodeCode()) ? branchList : new ArrayList<>();
            if (nodeEntity != null) {
                taskNode.setNodeNext(nodeEntity.getNodeNext());
                taskNode.setState(nodeEntity.getState());
                taskNode.setSortCode(nodeEntity.getSortCode());
            }
            if (candidatesList.size() > 0) {
                taskNode.setCandidates(JsonUtil.getObjectToString(candidatesList));
            }
            //判断条件下是否选择分支
            ConditionList conditionList = conditionListAll.stream().filter(t -> taskNode.getNodeNext().equals(t.getFlowId())).findFirst().orElse(null);
            if (conditionList != null) {
                ChildNodeList nodeModel = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
                nodeModel.getCustom().setFlow(conditionList.getFlow());
                nodeModel.getCustom().setBranchFlow(conditionList.getBranchFlow());
                nodeModel.getCustom().setFlowId(conditionList.getFlowId());
                taskNode.setNodePropertyJson(JsonUtil.getObjectToString(nodeModel));
            }
        }
        flowTaskNodeService.updateTaskNode(flowTaskNodeListAll);
    }

    //---------------拒绝-------------------

    /**
     * 驳回获取节点下所有节点
     *
     * @param rejectNodeList
     * @param rejectList
     * @param taskNodeList
     */
    public void upAll(Set<String> rejectNodeList, List<String> rejectList, List<FlowTaskNodeEntity> taskNodeList) {
        List<FlowTaskNodeEntity> nodeList = taskNodeList.stream().filter(t -> rejectList.contains(t.getId())).collect(Collectors.toList());
        for (FlowTaskNodeEntity taskNode : nodeList) {
            List<String> list = StringUtil.isNotEmpty(taskNode.getNodeNext()) ? Arrays.asList(taskNode.getNodeNext().split(",")) : new ArrayList<>();
            List<FlowTaskNodeEntity> taskList = taskNodeList.stream().filter(t -> list.contains(t.getNodeCode())).collect(Collectors.toList());
            List<String> rejectListAll = taskList.stream().map(t -> t.getId()).collect(Collectors.toList());
            rejectNodeList.add(taskNode.getId());
            upAll(rejectNodeList, rejectListAll, taskNodeList);
        }
    }

    /**
     * 审批驳回节点
     *
     * @param nodeListAll 所有节点
     * @param taskNode    审批节点
     * @param isReject    是否驳回
     * @param thisStepAll 当前节点
     * @param thisStepId  任务当前节点
     * @return
     */
    public List<FlowTaskNodeEntity> isUpAll(List<FlowTaskNodeEntity> nodeListAll, FlowTaskNodeEntity taskNode, boolean isReject, Set<FlowTaskNodeEntity> thisStepAll, String[] thisStepId) throws WorkFlowException {
        List<FlowTaskNodeEntity> result = new ArrayList<>();
        List<FlowTaskNodeEntity> resultList = new ArrayList<>();
        List<String> thisStepIdAll = new ArrayList<>(Arrays.asList(thisStepId));
        if (isReject) {
            if (FlowNature.START.equals(taskNode.getNodeUp())) {
                List<FlowTaskNodeEntity> startNode = nodeListAll.stream().filter(t -> FlowNature.NodeStart.equals(t.getNodeType())).collect(Collectors.toList());
                result.addAll(startNode);
            } else if (FlowNature.UP.equals(taskNode.getNodeUp())) {
                List<FlowTaskNodeEntity> nodeList = nodeListAll.stream().filter(t -> StringUtil.isNotEmpty(t.getNodeNext()) && t.getNodeNext().contains(taskNode.getNodeCode())).collect(Collectors.toList());
                result.addAll(nodeList);
                Set<String> rejectNodeList = new HashSet<>();
                List<String> reject = nodeList.stream().map(FlowTaskNodeEntity::getId).collect(Collectors.toList());
                this.upAll(rejectNodeList, reject, nodeListAll);
                List<String> delNode = nodeListAll.stream().filter(t -> rejectNodeList.contains(t.getId())).map(FlowTaskNodeEntity::getNodeCode).collect(Collectors.toList());
                thisStepIdAll.removeAll(delNode);
                List<FlowTaskNodeEntity> stepId = nodeListAll.stream().filter(t -> thisStepIdAll.contains(t.getNodeCode())).collect(Collectors.toList());
                result.addAll(stepId);
            } else {
                List<FlowTaskNodeEntity> taskNodeList = nodeListAll.stream().filter(t -> t.getNodeCode().equals(taskNode.getNodeUp())).collect(Collectors.toList());
                result.addAll(taskNodeList);
            }
            result = result.stream().sorted(Comparator.comparing(FlowTaskNodeEntity::getSortCode).reversed()).collect(Collectors.toList());
            boolean isChild = result.stream().anyMatch(t -> FlowNature.NodeSubFlow.equals(t.getNodeType()));
            if (isChild) {
                throw new WorkFlowException(MsgCode.WF114.get());
            }
            resultList.addAll(result);
            boolean start = result.stream().filter(t -> FlowNature.NodeStart.equals(t.getNodeType())).count() > 0;
            if (!start) {
                List<FlowTaskOperatorEntity> taskOperatorList = flowTaskOperatorService.getList(taskNode.getTaskId()).stream().filter(t -> FlowNodeEnum.Process.getCode().equals(t.getState())).collect(Collectors.toList());
                List<String> taskNodeList = taskOperatorList.stream().map(FlowTaskOperatorEntity::getTaskNodeId).collect(Collectors.toList());
                List<FlowTaskNodeEntity> delNodeList = nodeListAll.stream().filter(t -> !taskNodeList.contains(t.getId())).collect(Collectors.toList());
                result.removeAll(delNodeList);
            }
            if (result.size() == 0) {
                result.addAll(resultList);
            }
        }
        thisStepAll.addAll(result);
        return result;
    }

    //-----------------------子节点---------------------------------

    /**
     * 拒绝比例
     *
     * @param taskNode 节点实体
     * @return
     */
    public boolean isReject(FlowTaskNodeEntity taskNode) {
        List<FlowTaskOperatorEntity> operatorList = flowTaskOperatorService.getList(taskNode.getTaskId()).stream().filter(t -> t.getTaskNodeId().equals(taskNode.getId()) && FlowNodeEnum.Process.getCode().equals(t.getState())).collect(Collectors.toList());
        ChildNodeList nodeModel = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
        Properties properties = nodeModel.getProperties();
        List<String> operatorIdList = operatorList.stream().filter(t -> FlowNature.ParentId.equals(t.getParentId())).map(FlowTaskOperatorEntity::getId).collect(Collectors.toList());
        this.improperApprover(nodeModel, operatorList, operatorIdList);
        long pass = 100 - properties.getCountersignRatio();
        double total = operatorList.stream().filter(t -> FlowNature.ParentId.equals(t.getParentId())).count();
        List<FlowTaskOperatorEntity> passNumList = this.passNum(operatorList, FlowNature.RejectCompletion);
        double passNum = passNumList.size();
        boolean isCountersign = this.isCountersign(pass, total, passNum);
        return isCountersign;
    }

    /**
     * 判断子流程是否全部走完，进行主流程任务
     *
     * @param flowTask 子流程任务
     * @throws WorkFlowException
     */
    public boolean isNext(FlowTaskEntity flowTask, FlowModel flowModel) throws WorkFlowException {
        //子流程结束，触发主流程
        if (!FlowNature.ParentId.equals(flowTask.getParentId()) && StringUtil.isNotEmpty(flowTask.getParentId())) {
            FlowTaskEntity parentFlowTask = flowTaskService.getInfo(flowTask.getParentId());
            FlowTaskOperatorEntity parentOperator = new FlowTaskOperatorEntity();
            boolean isAudit = this.updateTaskNode(parentFlowTask, flowTask.getId(), parentOperator, flowModel);
            FlowModel parentModel = new FlowModel();
            parentModel.setIsAsync(true);
            Map<String, Object> data = new HashMap<>(16);
            parentModel.setFormData(data);
            parentModel.setUserInfo(flowModel.getUserInfo());
            if (isAudit) {
                flowTaskNewService.audit(parentFlowTask, parentOperator, parentModel);
            }
        }
        return true;
    }

    /**
     * 子节点审批人
     *
     * @param taskChild
     * @return
     */
    public List<UserEntity> childSaveList(TaskChild taskChild) {
        ChildNodeList childNode = taskChild.getChildNode();
        FlowTaskEntity taskEntity = taskChild.getFlowTask();
        boolean verify = taskChild.getVerify();
        //赋值子流程
        String createUserId = taskEntity.getCreatorUserId();
        Properties properties = childNode.getProperties();
        Integer errorRule = properties.getErrorRule();
        String type = properties.getInitiateType();
        List<String> userIdAll = new ArrayList<>();
        Date date = new Date();
        TaskOperatoUser taskOperatoUser = new TaskOperatoUser();
        taskOperatoUser.setDate(date);
        taskOperatoUser.setChildNode(childNode);
        //发起者【部门主管】
        if (FlowTaskOperatorEnum.DepartmentCharge.getCode().equals(type)) {
            UserEntity userEntity = serviceUtil.getUserInfo(createUserId);
            if (userEntity != null) {
                OrganizeEntity organizeEntity = getManageOrgByLevel(userEntity.getOrganizeId(), properties.getDepartmentLevel());
                if (organizeEntity != null) {
                    userIdAll.add(organizeEntity.getManager());
                }
            }
        }
        //发起者【发起者主管】
        if (FlowTaskOperatorEnum.LaunchCharge.getCode().equals(type)) {
            //时时查用户主管
            UserEntity info = serviceUtil.getUserInfo(createUserId);
            if (info != null) {
                userIdAll.add(getManagerByLevel(info.getManagerId(), properties.getManagerLevel()));
            }
        }
        //【发起本人】
        if (FlowTaskOperatorEnum.InitiatorMe.getCode().equals(type)) {
            userIdAll.add(createUserId);
        }
        //【变量】
        if (FlowTaskOperatorEnum.Variate.getCode().equals(type)) {
            Map<String, Object> dataAll = JsonUtil.stringToMap(taskEntity.getFlowFormContentJson());
            Object data = dataAll.get(properties.getFormField());
            if (data != null) {
                String formFieldType = properties.getFormFieldType();
                List<String> handleIdAll = new ArrayList<>();
                if ("1".equals(formFieldType)) {
                    try {
                        handleIdAll.addAll(JsonUtil.getJsonToList(String.valueOf(data), String.class));
                    } catch (Exception e) {

                    }
                    if (data instanceof List) {
                        handleIdAll.addAll((List) data);
                    } else {
                        handleIdAll.addAll(Arrays.asList(String.valueOf(data).split(",")));
                    }
                } else {
                    List<String> list = new ArrayList<>();
                    try {
                        list.addAll(JsonUtil.getJsonToList(String.valueOf(data), String.class));
                    } catch (Exception e) {

                    }
                    if (data instanceof List) {
                        list.addAll((List) data);
                    } else {
                        list.addAll(Arrays.asList(String.valueOf(data).split(",")));
                    }
                    List<UserRelationEntity> listByObjectIdAll = serviceUtil.getListByObjectIdAll(list);
                    List<String> userPosition = listByObjectIdAll.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
                    handleIdAll.addAll(userPosition);
                }
                userIdAll.addAll(handleIdAll);
            }
        }
        //【环节】
        if (FlowTaskOperatorEnum.Tache.getCode().equals(type)) {
            List<FlowTaskOperatorRecordEntity> operatorUserList = flowTaskOperatorRecordService.getList(taskEntity.getId()).stream().filter(t -> properties.getNodeId().equals(t.getNodeCode()) && FlowRecordEnum.audit.getCode().equals(t.getHandleStatus()) && FlowNodeEnum.Process.getCode().equals(t.getStatus())).collect(Collectors.toList());
            List<String> handleId = operatorUserList.stream().map(FlowTaskOperatorRecordEntity::getHandleId).collect(Collectors.toList());
            userIdAll.addAll(handleId);
        }
        //【服务】
        if (FlowTaskOperatorEnum.Serve.getCode().equals(type)) {
            String url = properties.getGetUserUrl() + "?" + taskNodeId + "=" + childNode.getTaskNodeId() + "&" + taskId + "=" + childNode.getTaskId();
            String token = UserProvider.getToken();
            JSONObject object = HttpUtil.httpRequest(url, "GET", null, token);
            if (object != null) {
                if (object.get("data") != null) {
                    JSONObject data = object.getJSONObject("data");
                    List<String> handleId = StringUtil.isNotEmpty(data.getString("handleId")) ? Arrays.asList(data.getString("handleId").split(",")) : new ArrayList<>();
                    userIdAll.addAll(handleId);
                }
            }
        }
        //【指定用户】
        userIdAll.addAll(properties.getInitiator());
        //【指定岗位】
        List<String> positionList = properties.getInitiatePos();
        //【指定角色】
        List<String> roleList = properties.getInitiateRole();
        //【指定部门】
        List<String> orgList = properties.getInitiateOrg();
        //【指定分组】
        List<String> groupList = properties.getInitiateGroup();
        List<String> list = new ArrayList<>();
        list.addAll(positionList);
        list.addAll(roleList);
        list.addAll(orgList);
        list.addAll(groupList);
        List<UserRelationEntity> listByObjectIdAll = serviceUtil.getListByObjectIdAll(list);
        List<String> handleId = listByObjectIdAll.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
        userIdAll.addAll(handleId);
        List<UserEntity> userList = serviceUtil.getUserName(userIdAll, true);
        //异常处理规则
        List<String> errList = new ArrayList<>();
        switch (FlowErrorRuleEnum.getByCode(errorRule)) {
            case administrator:
            case notSubmit:
            case pass:
                errList.add(user);
                break;
            case initiator:
                List<UserEntity> errorRuleUser = serviceUtil.getUserName(properties.getErrorRuleUser(), true);
                if (errorRuleUser.size() > 0) {
                    errList.addAll(errorRuleUser.stream().map(UserEntity::getId).collect(Collectors.toList()));
                } else {
                    errList.add(user);
                }
                break;
            case creatorUserId:
                errList.add(createUserId);
                break;
            default:
                break;
        }
        if (userList.size() == 0 && verify) {
            userList.addAll(serviceUtil.getUserName(errList, true));
        }
        if (userList.size() == 0 && !verify) {
            List<String> childUserIdAll = new ArrayList<>();
            childUserIdAll.addAll(childNode.getCustom().getTaskId());
            childUserIdAll.addAll(childNode.getCustom().getAsyncTaskList());
            List<String> childList = flowTaskService.getOrderStaList(childUserIdAll).stream().map(FlowTaskEntity::getCreatorUserId).collect(Collectors.toList());
            userList.addAll(serviceUtil.getUserName(childList));
        }
        return userList;
    }

    /**
     * 赋值
     *
     * @param data     数据
     * @param engine   引擎
     * @param parentId 上一节点
     * @return
     */
    public FlowModel assignment(Map<String, Object> data, FlowEngineEntity engine, String parentId, String title) {
        FlowModel flowModel = new FlowModel();
        String billNo = "单据规则不存在";
        if (FlowNature.CUSTOM.equals(engine.getFormType())) {
            FormDataModel formData = JsonUtil.getJsonToBean(engine.getFormData(), FormDataModel.class);
            List<FieLdsModel> list = JsonUtil.getJsonToList(formData.getFields(), FieLdsModel.class);
            List<FormAllModel> formAllModel = new ArrayList<>();
            List<TableModel> tableModelList = JsonUtil.getJsonToList(engine.getFlowTables(), TableModel.class);
            RecursionForm recursionForm = new RecursionForm(list, tableModelList);
            FormCloumnUtil.recursionForm(recursionForm, formAllModel);
            List<FormAllModel> mastForm = formAllModel.stream().filter(t -> FormEnum.mast.getMessage().equals(t.getJnpfKey())).collect(Collectors.toList());
            FormAllModel formModel = mastForm.stream().filter(t -> JnpfKeyConsts.BILLRULE.equals(t.getFormColumnModel().getFieLdsModel().getConfig().getJnpfKey())).findFirst().orElse(null);
            try {
                if (formModel != null) {
                    FieLdsModel fieLdsModel = formModel.getFormColumnModel().getFieLdsModel();
                    String ruleKey = fieLdsModel.getConfig().getRule();
                    billNo = serviceUtil.getBillNumber(ruleKey);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        flowModel.setFormData(data);
        flowModel.setParentId(parentId);
        flowModel.setProcessId(RandomUtil.uuId());
        flowModel.setBillNo(billNo);
        flowModel.setFlowTitle(title);
        return flowModel;
    }

    /**
     * 子表表单赋值
     *
     * @param engine     子表引擎
     * @param flowModel  提交数据
     * @param assignList 数据传递
     * @param isCustom   true自定义表单 false系统表单
     * @return
     */
    public Map<String, Object> childData(FlowEngineEntity engine, FlowModel flowModel, List<FlowAssignModel> assignList, boolean isCustom) {
        Map<String, Object> result = new HashMap<>(16);
        Map<String, Object> formData = flowModel.getFormData();
        result.putAll(formData);
        if (engine != null) {
            for (FlowAssignModel assignMode : assignList) {
                String parentField = assignMode.getParentField();
                String[] parentList = parentField.split("-");
                Object data = formData.get(parentField);
                if (parentList.length > 1) {
                    if (formData.get(parentList[0]) instanceof List) {
                        List<Object> datas = new ArrayList<>();
                        List<Map<String, Object>> childData = (List<Map<String, Object>>) formData.get(parentList[0]);
                        for (Map<String, Object> map : childData) {
                            datas.add(map.get(parentList[1]));
                        }
                        data = datas;
                    }
                }
                String childField = assignMode.getChildField();
                result.put(childField, data);
            }
        }
        return result;
    }

    /**
     * 子流程完成了修改父节点的状态
     */
    public boolean updateTaskNode(FlowTaskEntity parentFlowTask, String taskId, FlowTaskOperatorEntity parentOperator, FlowModel flowModel) {
        List<FlowTaskNodeEntity> flowTaskNodeAll = flowTaskNodeService.getList(parentFlowTask.getId());
        List<FlowTaskNodeEntity> taskNodeList = flowTaskNodeAll.stream().filter(t -> FlowNodeEnum.Process.getCode().equals(t.getState())).collect(Collectors.toList());
        List<FlowTaskNodeEntity> result = new ArrayList<>();
        flowModel.setFreeApproverUserId(null);
        for (FlowTaskNodeEntity nodeEntity : taskNodeList) {
            ChildNodeList parentNode = JsonUtil.getJsonToBean(nodeEntity.getNodePropertyJson(), ChildNodeList.class);
            List<String> taskIdAll = parentNode.getCustom().getTaskId();
            boolean isNum = taskIdAll.contains(taskId);
            boolean isEnd = flowTaskService.getOrderStaList(taskIdAll).stream().filter(t -> !FlowTaskStatusEnum.Adopt.getCode().equals(t.getStatus())).count() == 0;
            if (isNum && isEnd) {
                this.parentOperator(parentOperator, nodeEntity);
                List<FlowTaskNodeEntity> nextNode = new ArrayList<>();
                nextNode.addAll(taskNodeList.stream().filter(t -> nodeEntity.getNodeNext().contains(t.getNodeCode())).collect(Collectors.toList()));
                result.addAll(this.isNextAll(taskNodeList, nextNode, nodeEntity, flowModel));
            }
        }
        return result.size() > 0;
    }

    //----------------------撤回--------------------------

    /**
     * 赋值审批数据
     *
     * @param parentOperator
     * @param nodeEntity
     */
    public void parentOperator(FlowTaskOperatorEntity parentOperator, FlowTaskNodeEntity nodeEntity) {
        parentOperator.setTaskNodeId(nodeEntity.getId());
        parentOperator.setDescription(JsonUtil.getObjectToString(new ArrayList<>()));
        parentOperator.setNodeCode(nodeEntity.getNodeCode());
        parentOperator.setNodeName(nodeEntity.getNodeName());
        parentOperator.setTaskId(nodeEntity.getTaskId());
        parentOperator.setCompletion(FlowNature.ProcessCompletion);
        parentOperator.setSortCode(1L);
    }


    //----------------------变更、复活--------------------------

    /**
     * 修改下一节点
     *
     * @param nodeListAll
     * @param nodeEntity
     * @param revive
     */
    public void change(List<FlowTaskNodeEntity> nodeListAll, FlowTaskNodeEntity nodeEntity, boolean revive, int completion, FlowModel flowModel) {
        if (nodeEntity != null) {
            List<String> next = Arrays.asList(String.valueOf(nodeEntity.getNodeNext()).split(","));
            for (String id : next) {
                FlowTaskNodeEntity nextNode = nodeListAll.stream().filter(t -> t.getNodeCode().equals(id)).findFirst().orElse(null);
                if (nextNode != null) {
                    ChildNodeList nodeModel = JsonUtil.getJsonToBean(nextNode.getNodePropertyJson(), ChildNodeList.class);
                    nextNode.setCompletion(completion);
                    flowTaskNodeService.update(nextNode);
                    if (FlowNature.NodeSubFlow.equals(nextNode.getNodeType())) {
                        if (!revive) {
                            //同步
                            List<String> idAll = nodeModel.getCustom().getTaskId();
                            flowTaskService.deleteChildAll(idAll);
                        }
                    }
                    this.change(nodeListAll, nextNode, revive, completion, flowModel);
                }
            }
        }
    }

    //---------------------公共方法--------------------------

    /**
     * 递归获取加签人
     *
     * @param id
     * @param operatorList
     */
    public void getOperator(String id, Set<FlowTaskOperatorEntity> operatorList) {
        if (StringUtil.isNotEmpty(id)) {
            List<FlowTaskOperatorEntity> operatorListAll = flowTaskOperatorService.getParentId(id);
            for (FlowTaskOperatorEntity operatorEntity : operatorListAll) {
                operatorEntity.setState(FlowNodeEnum.Futility.getCode());
                operatorList.add(operatorEntity);
                this.getOperator(operatorEntity.getId(), operatorList);
            }
        }
    }

    /**
     * 更新当前节点
     *
     * @param nextOperatorList 下一审批节点
     * @param flowTask         流程任务
     */
    public boolean getNextStepId(List<ChildNodeList> nextOperatorList, FlowTaskEntity flowTask, FlowModel flowModel) throws WorkFlowException {
        boolean isEnd = false;
        Set<String> delNodeList = new HashSet<>();
        List<String> progressList = new ArrayList<>();
        List<String> nextOperator = new ArrayList<>();
        ChildNodeList end = nextOperatorList.stream().filter(t -> t.getCustom().getNodeId().contains(FlowNature.NodeEnd)).findFirst().orElse(null);
        List<FlowTaskNodeEntity> flowTaskNodeList = flowTaskNodeService.getList(flowTask.getId()).stream().filter(t -> FlowNodeEnum.Process.getCode().equals(t.getState())).collect(Collectors.toList());
        for (ChildNodeList childNode : nextOperatorList) {
            Properties properties = childNode.getProperties();
            String id = childNode.getCustom().getNodeId();
            String progress = properties.getProgress();
            List<FlowTaskNodeEntity> taskNodeList = flowTaskNodeList.stream().filter(t -> StringUtil.isNotEmpty(t.getNodeNext()) && t.getNodeNext().contains(id)).collect(Collectors.toList());
            List<String> nodeList = taskNodeList.stream().map(FlowTaskNodeEntity::getNodeCode).collect(Collectors.toList());
            delNodeList.addAll(nodeList);
            boolean isAddNext = flowTaskNodeList.stream().filter(t -> t.getId().equals(childNode.getTaskNodeId()) && FlowNature.ProcessCompletion.equals(t.getCompletion())).count() > 0;
            if (isAddNext) {
                nextOperator.add(id);
            }
            if (StringUtil.isNotEmpty(progress)) {
                progressList.add(progress);
            }
        }
        String[] thisNode = flowTask.getThisStepId() != null ? flowTask.getThisStepId().split(",") : new String[]{};
        Set<String> thisStepId = new HashSet<>();
        for (String id : thisNode) {
            boolean isStepId = flowTaskNodeList.stream().filter(t -> t.getNodeCode().equals(id) && FlowNature.ProcessCompletion.equals(t.getCompletion())).count() > 0;
            if (isStepId) {
                thisStepId.add(id);
            }
        }
        thisStepId.removeAll(delNodeList);
        thisStepId.addAll(nextOperator);
        List<String> thisNodeName = new ArrayList<>();
        for (String id : thisStepId) {
            List<String> nodeList = flowTaskNodeList.stream().filter(t -> t.getNodeCode().equals(id)).map(FlowTaskNodeEntity::getNodeName).collect(Collectors.toList());
            thisNodeName.addAll(nodeList);
        }
        flowTask.setThisStepId(String.join(",", thisStepId));
        flowTask.setThisStep(String.join(",", thisNodeName));
        Collections.sort(progressList);
        flowTask.setCompletion(progressList.size() > 0 ? Integer.valueOf(progressList.get(0)) : null);
        if (end != null) {
            isEnd = this.endround(flowTask, end, flowModel);
        }
        return isEnd;
    }

    /**
     * 审核记录
     *
     * @param record         审批实例
     * @param operatordModel 对象数据
     */
    public void operatorRecord(FlowTaskOperatorRecordEntity record, FlowOperatordModel operatordModel) {
        int status = operatordModel.getStatus();
        FlowModel flowModel = operatordModel.getFlowModel();
        String userId = operatordModel.getUserId();
        FlowTaskOperatorEntity operator = operatordModel.getOperator();
        String operatorId = operatordModel.getOperatorId();
        record.setHandleOpinion(flowModel.getHandleOpinion());
        record.setHandleId(userId);
        record.setHandleTime(new Date());
        record.setHandleStatus(status);
        record.setOperatorId(operatorId);
        record.setNodeCode(operator.getNodeCode());
        record.setNodeName(operator.getNodeName() != null ? operator.getNodeName() : "开始");
        record.setTaskOperatorId(operator.getId());
        record.setTaskNodeId(operator.getTaskNodeId());
        record.setTaskId(operator.getTaskId());
        record.setSignImg(flowModel.getSignImg());
        record.setFileList(flowModel.getFileList());
        boolean freeApprover = !FlowNature.ParentId.equals(operator.getParentId());
        record.setStatus(freeApprover ? FlowNodeEnum.FreeApprover.getCode() : FlowNodeEnum.Process.getCode());
    }

    /**
     * 定时器
     *
     * @param taskOperator 流程经办
     * @param taskNodeList 所有流程节点
     * @param operatorList 下一流程经办
     * @return
     */
    public List<FlowTaskOperatorEntity> timer(FlowTaskOperatorEntity taskOperator, List<FlowTaskNodeEntity> taskNodeList, List<FlowTaskOperatorEntity> operatorList) {
        List<FlowTaskOperatorEntity> operatorListAll = new ArrayList<>();
        FlowTaskNodeEntity taskNode = taskNodeList.stream().filter(t -> t.getId().equals(taskOperator.getTaskNodeId())).findFirst().orElse(null);
        if (taskNode != null) {
            //获取其他分流的定时器
            List<String> nodeList = taskNodeList.stream().filter(t -> t.getSortCode().equals(taskNode.getSortCode())).map(FlowTaskNodeEntity::getId).collect(Collectors.toList());
            List<FlowTaskOperatorEntity> operatorAll = flowTaskOperatorService.getList(taskOperator.getTaskId());
            Set<Date> dateListAll = new HashSet<>();
            List<FlowTaskOperatorEntity> list = operatorAll.stream().filter(t -> nodeList.contains(t.getTaskNodeId())).collect(Collectors.toList());
            for (FlowTaskOperatorEntity operator : list) {
                if (StringUtil.isNotEmpty(operator.getDescription())) {
                    List<Date> dateList = JsonUtil.getJsonToList(operator.getDescription(), Date.class);
                    dateListAll.addAll(dateList);
                }
            }
            //获取单前审批定时器
            if (StringUtil.isNotEmpty(taskOperator.getDescription())) {
                List<Date> date = JsonUtil.getJsonToList(taskOperator.getDescription(), Date.class);
                dateListAll.addAll(date);
            }
            for (FlowTaskOperatorEntity operator : operatorList) {
                if (FlowNature.ParentId.equals(operator.getParentId())) {
                    operator.setDescription(JsonUtil.getObjectToString(dateListAll));
                }
                operatorListAll.add(operator);
            }
        }
        return operatorListAll;
    }

    /**
     * 验证必填
     *
     * @param nodeModel 节点
     * @param formData
     * @return
     */
    public boolean requestData(ChildNodeList nodeModel, Map<String, Object> formData) {
//        List<FormOperates> formOperates = nodeModel.getProperties().getFormOperates().stream().filter(FormOperates::isRequired).collect(Collectors.toList());
        boolean flag = false;
//        for (FormOperates formOperate : formOperates) {
//            String model = formOperate.getId();
//            Object data = formData.get(model);
//            if (ObjectUtil.isEmpty(data)) {
//                flag = true;
//                break;
//            }
//        }
        return flag;
    }

    /**
     * 更新节点数据
     */
    public void updateNodeList(FlowUpdateNode flowUpdateNode) {
        FlowTaskEntity flowTask = flowUpdateNode.getFlowTask();
        ChildNode childNodeAll = flowUpdateNode.getChildNodeAll();
        List<ChildNodeList> nodeListAll = flowUpdateNode.getNodeListAll();
        List<ConditionList> conditionListAll = flowUpdateNode.getConditionListAll();
        List<FlowTaskNodeEntity> taskNodeList = flowUpdateNode.getTaskNodeList();
        UserInfo userInfo = flowUpdateNode.getUserInfo();
        FlowJsonUtil.getTemplateAll(childNodeAll, nodeListAll, conditionListAll);
        boolean submit = flowUpdateNode.isSubmit();
        this.createNodeList(flowTask, nodeListAll, conditionListAll, taskNodeList, userInfo, submit);
    }

    /**
     * 下一审批人
     *
     * @throws WorkFlowException 异常
     */
    public Map<String, List<String>> nextOperator(FlowOperator flowOperator) throws WorkFlowException {
        List<FlowTaskOperatorEntity> operatorListAll = flowOperator.getOperatorListAll();
        List<ChildNodeList> nodeList = flowOperator.getNodeList();
        FlowTaskEntity flowTask = flowOperator.getFlowTask();
        FlowModel flowModel = flowOperator.getFlowModel();
        Map<String, List<String>> asyncTaskList = flowOperator.getAsyncTaskList();
        UserInfo userInfo = flowOperator.getUserInfo();
        List<FlowTaskNodeEntity> taskNodeListAll = flowOperator.getTaskNodeListAll();
        Map<String, List<String>> taskNode = new HashMap<>(16);
        List<FlowErrorModel> errorList = new ArrayList<>();
        //查询审批人
        for (ChildNodeList childNode : nodeList) {
            //封装查询对象
            TaskOperator taskOperator = new TaskOperator();
            taskOperator.setChildNode(childNode);
            taskOperator.setTaskNodeList(taskNodeListAll);
            taskOperator.setTaskEntity(flowTask);
            taskOperator.setFlowModel(flowModel);
            taskOperator.setId(flowModel.getOperatorId());
            taskOperator.setUserInfo(userInfo);
            taskOperator.setExtraRule(true);
            taskOperator.setErrorRule(true);
            taskOperator.setReject(flowOperator.isReject());
            //判断节点属性
            List<FlowTaskOperatorEntity> operatorList = new ArrayList<>();
            Custom custom = childNode.getCustom();
            Properties properties = childNode.getProperties();
            String type = custom.getType();
            String flowId = properties.getFlowId();
            List<FlowAssignModel> assignList = childNode.getProperties().getAssignList();
            //判断子流程
            boolean isChild = FlowNature.NodeSubFlow.equals(type);
            if (isChild) {
                List<ChildNodeList> childNodeListAll = new ArrayList<>();
                this.candidate(taskNodeListAll, childNodeListAll, custom.getNodeId(), true);
                int num = 0;
                List<String> branchList = flowModel.getBranchList() != null ? flowModel.getBranchList() : new ArrayList<>();
                for (ChildNodeList childNodeList : childNodeListAll) {
                    String nodeId = childNodeList.getCustom().getNodeId();
                    boolean nextNode = branchList.size() > 0 ? branchList.contains(nodeId) : true;
                    if (!FlowNature.NodeEnd.equals(nodeId) && nextNode) {
                        taskOperator.setChildNode(childNodeList);
                        List<String> userIdAll = this.userListAll(taskOperator);
                        List<UserEntity> userList = serviceUtil.getUserName(userIdAll, true);
                        if (userList.size() == 0) {
                            num += taskOperator.getNotSubmit() > 0 ? 1 : 0;
                            if (taskOperator.getNode() > 0) {
                                FlowErrorModel errorModel = new FlowErrorModel();
                                errorModel.setNodeId(nodeId);
                                errorModel.setNodeName(childNodeList.getProperties().getTitle());
                                errorList.add(errorModel);
                            }
                        }
                    }
                }
                if (num > 0) {
                    throw new WorkFlowException("下一节点无审批人员请联系管理员！");
                }
                //判断当前流程引擎类型
                FlowEngineEntity parentEngine = flowEngineService.getInfo(flowTask.getFlowId());
                boolean isCustom = FlowNature.CUSTOM.equals(parentEngine.getFormType());
                List<String> taskNodeList = new ArrayList<>();
                List<String> asyncTaskNodeList = new ArrayList<>();
                FlowEngineEntity engine = flowEngineService.getInfo(flowId);
                //创建子流程
                Map<String, Object> data = this.childData(engine, flowModel, assignList, isCustom);
                data.put("flowId", flowId);
                data.put("version", 0);
                //子节点审批人
                TaskChild taskChild = new TaskChild();
                taskChild.setChildNode(childNode);
                taskChild.setFlowTask(flowTask);
                taskChild.setEngine(engine);
                taskChild.setFlowModel(flowModel);
                List<UserEntity> list = this.childSaveList(taskChild);
                errorList.addAll(taskChild.getErrorList());
                if (errorList.size() == 0) {
                    //子流程消息
                    List<FlowTaskNodeEntity> childTaskNodeAll = flowTaskNodeService.getList(flowTask.getId());
                    List<FlowTaskOperatorEntity> childOperatorList = new ArrayList<>();
                    FlowMsgModel flowMsgModel = new FlowMsgModel();
                    flowMsgModel.setCirculateList(new ArrayList<>());
                    flowMsgModel.setNodeList(childTaskNodeAll);
                    flowMsgModel.setData(flowModel.getFormData());
                    flowMsgModel.setWait(false);
                    flowMsgModel.setLaunch(true);
                    boolean isAsync = properties.getIsAsync();
                    FlowTaskNodeEntity taskNodeEntity = flowTaskNodeService.getInfo(childNode.getTaskNodeId());
                    //子流程数据整合
                    if (isAsync) {
                        FlowModel parentModel = new FlowModel();
                        parentModel.setUserId("");
                        parentModel.setFormData(data);
                        parentModel.setIsAsync(properties.getIsAsync());
                        parentModel.setUserInfo(userInfo);
                        FlowTaskOperatorEntity parentOperator = new FlowTaskOperatorEntity();
                        this.parentOperator(parentOperator, taskNodeEntity);
                        flowTaskNewService.audit(flowTask, parentOperator, parentModel);
                        taskNodeEntity.setCompletion(FlowNature.AuditCompletion);
                        flowTaskNodeService.update(taskNodeEntity);
                    }
                    for (UserEntity entity : list) {
                        String title = entity.getRealName() + "的" + engine.getFullName() + "(子流程)";
                        FlowModel nextFlowModel = this.assignment(data, parentEngine, flowTask.getId(), title);
                        nextFlowModel.setUserId(entity.getId());
                        nextFlowModel.setFlowTitle(title);
                        nextFlowModel.setFormData(data);
                        nextFlowModel.setIsAsync(properties.getIsAsync());
                        nextFlowModel.setFlowId(engine.getId());
                        nextFlowModel.setUserInfo(userInfo);
                        FlowTaskEntity childTaskEntity = flowTaskNewService.save(nextFlowModel);
                        this.createData(engine, childTaskEntity, nextFlowModel);
                        FlowTaskOperatorEntity parentOperator = new FlowTaskOperatorEntity();
                        this.parentOperator(parentOperator, taskNodeEntity);
                        if (!isAsync) {
                            //同步
                            taskNodeList.add(nextFlowModel.getProcessId());
                        } else {
                            asyncTaskNodeList.add(nextFlowModel.getProcessId());
                        }
                        parentOperator.setHandleId(entity.getId());
                        parentOperator.setTaskId(nextFlowModel.getProcessId());
                        childOperatorList.add(parentOperator);
                        //发送子流程消息
                        List<FlowTaskOperatorEntity> launchList = new ArrayList<>();
                        FlowTaskEntity taskEntity = new FlowTaskEntity();
                        taskEntity.setFullName(title);
                        launchList.add(parentOperator);
                        flowMsgModel.setOperatorList(launchList);
                        flowMsgModel.setEngine(engine);
                        flowMsgModel.setTaskEntity(taskEntity);
                        flowMsgModel.setFlowModel(flowModel);
                        flowMsgUtil.message(flowMsgModel);
                    }
                    taskNode.put(childNode.getTaskNodeId(), taskNodeList);
                    asyncTaskList.put(childNode.getTaskNodeId(), asyncTaskNodeList);
                }
            } else {
                if (!FlowNature.NodeEnd.equals(childNode.getCustom().getNodeId())) {
                    List<String> taskIdList = nodeList.stream().map(ChildNodeList::getTaskNodeId).collect(Collectors.toList());
                    List<FlowTaskNodeEntity> flowTaskNodeList = taskNodeListAll.stream().filter(t -> taskIdList.contains(t.getId())).collect(Collectors.toList());
                    List<String> brachListAll = new ArrayList<>();
                    List<String> taskBrachList = new ArrayList<>();
                    flowTaskNodeList.stream().forEach(t -> {
                        List<String> brachList = StringUtil.isNotEmpty(t.getCandidates()) ? JsonUtil.getJsonToList(t.getCandidates(), String.class) : new ArrayList<>();
                        brachListAll.addAll(brachList);
                        if (t.getId().equals(childNode.getTaskNodeId())) {
                            taskBrachList.addAll(brachList);
                        }
                    });
                    boolean isAdd = (brachListAll.size() > 0 && taskBrachList.size() == 0) ? false : true;
                    if (isAdd) {
                        this.operator(operatorList, taskOperator);
                        errorList.addAll(taskOperator.getErrorList());
                    }
                }
            }
            operatorListAll.addAll(operatorList);
        }
        if (errorList.size() > 0) {
            throw new WorkFlowException(200, JsonUtil.getObjectToString(errorList));
        }
        return taskNode;
    }

    /**
     * 审批人
     * taskOperator 对象
     *
     * @param operatorList
     * @param taskOperator
     */
    public List<UserEntity> operator(List<FlowTaskOperatorEntity> operatorList, TaskOperator taskOperator) throws WorkFlowException {
        ChildNodeList childNode = taskOperator.getChildNode();
        FlowTaskEntity flowTask = taskOperator.getTaskEntity();
        FlowModel flowModel = taskOperator.getFlowModel();
        UserInfo userInfo = taskOperator.getUserInfo();
        List<FlowTaskNodeEntity> taskNodeList = taskOperator.getTaskNodeList();
        boolean verify = taskOperator.getVerify();
        boolean reject = taskOperator.getReject();
        List<UserEntity> userAll = new ArrayList<>();
        Date date = new Date();
        List<FlowTaskOperatorEntity> nextList = new ArrayList<>();
        Properties properties = childNode.getProperties();
        String freeApproverUserId = flowModel.getFreeApproverUserId();
        TaskOperatoUser taskOperatoUser = new TaskOperatoUser();
        taskOperatoUser.setDate(date);
        taskOperatoUser.setChildNode(childNode);
        boolean isUser = StringUtil.isNotEmpty(freeApproverUserId);
        taskOperatoUser.setId(isUser ? taskOperator.getId() : FlowNature.ParentId);
        FlowTaskNodeEntity taskNodeEntity = flowTaskNodeService.getInfo(childNode.getTaskNodeId());
        int pass = 0;
        int notSubmit = 0;
        int node = 0;
        List<String> userIdAll = new ArrayList<>();
        //【加签】
        if (isUser) {
            userIdAll.add(freeApproverUserId);
            boolean details = taskOperator.getDetails();
            //加签记录
            if (details) {
                Custom custom = childNode.getCustom();
                FlowTaskOperatorRecordEntity operatorRecord = new FlowTaskOperatorRecordEntity();
                FlowTaskOperatorEntity operator = new FlowTaskOperatorEntity();
                operator.setTaskId(childNode.getTaskId());
                operator.setNodeCode(custom.getNodeId());
                operator.setNodeName(properties.getTitle());
                //审批数据赋值
                FlowOperatordModel flowOperatordModel = FlowOperatordModel.builder().status(FlowRecordEnum.copyId.getCode()).flowModel(flowModel).userId(userInfo.getUserId()).operator(operator).operatorId(freeApproverUserId).build();
                this.operatorRecord(operatorRecord, flowOperatordModel);
                flowTaskOperatorRecordService.create(operatorRecord);
            }
        } else {
            userIdAll.addAll(this.userListAll(taskOperator));
            pass = taskOperator.getPass();
            notSubmit = taskOperator.getNotSubmit();
            node = taskOperator.getNode();
        }
        List<UserEntity> userName = serviceUtil.getUserName(userIdAll, true);
        userAll.addAll(userName);
        if (verify) {
            FlowAgreeRuleModel ruleModel = FlowAgreeRuleModel.builder().operatorListAll(nextList).taskOperatoUser(taskOperatoUser).flowTask(flowTask).userName(userName).childNode(childNode).taskNodeList(taskNodeList).reject(reject).build();
            this.flowAgreeRule(ruleModel);
        }
        if (nextList.size() == 0 && verify) {
            boolean isPass = this.pass(taskNodeList, childNode.getCustom().getNodeId(), flowModel, flowTask);
            if (pass > 0) {
                //1.验证下一节点类型
                if (isPass) {
                    FlowModel parentModel = new FlowModel();
                    parentModel.setUserId("0");
                    parentModel.setFormData(JsonUtil.stringToMap(flowTask.getFlowFormContentJson()));
                    parentModel.setHandleOpinion("默认通过");
                    parentModel.setUserInfo(flowModel.getUserInfo());
                    FlowTaskOperatorEntity parentOperator = new FlowTaskOperatorEntity();
                    parentOperator.setParentId(FlowNature.ParentId);
                    this.parentOperator(parentOperator, taskNodeEntity);
                    flowTaskNewService.audit(flowTask, parentOperator, parentModel);
                } else {
                    taskOperatoUser.setHandLeId(user);
                    this.operatorUser(nextList, taskOperatoUser);
                }
            }
            if (notSubmit > 0) {
                throw new WorkFlowException("下一节点无审批人员请联系管理员！");
            }
            if (node > 0) {
                List<FlowErrorModel> errorList = new ArrayList() {{
                    FlowErrorModel errorModel = new FlowErrorModel();
                    errorModel.setNodeId(childNode.getCustom().getNodeId());
                    errorModel.setNodeName(childNode.getProperties().getTitle());
                    add(errorModel);
                }};
                taskOperator.setErrorList(errorList);
            }
        }
        operatorList.addAll(nextList);
        if (userAll.size() == 0 && !verify) {
            List<String> operatorUserList = flowTaskOperatorService.getList(childNode.getTaskId()).stream().filter(t -> FlowNodeEnum.Process.getCode().equals(t.getState()) && t.getTaskNodeId().equals(childNode.getTaskNodeId())).map(FlowTaskOperatorEntity::getHandleId).collect(Collectors.toList());
            userAll.addAll(serviceUtil.getUserName(operatorUserList));
        }
        return userAll;
    }

    /**
     * 验证自动通过
     *
     * @param ruleModel
     */
    public void flowAgreeRule(FlowAgreeRuleModel ruleModel) {
        FlowTaskEntity flowTask = ruleModel.getFlowTask();
        List<UserEntity> userName = ruleModel.getUserName();
        TaskOperatoUser taskOperatoUser = ruleModel.getTaskOperatoUser();
        List<FlowTaskOperatorEntity> nextList = ruleModel.getOperatorListAll();
        ChildNodeList childNode = ruleModel.getChildNode();
        List<FlowTaskNodeEntity> taskNodeList = ruleModel.getTaskNodeList();
        boolean reject = ruleModel.getReject();
        int sort = 0;
        String creatorUserId = flowTask.getCreatorUserId();
        Properties properties = childNode.getProperties();
        List<Integer> statusList = new ArrayList() {{
            add(FlowNodeEnum.Process.getCode());
            add(FlowNodeEnum.FreeApprover.getCode());
        }};
        List<FlowTaskOperatorRecordEntity> recordList = flowTaskOperatorRecordService.getList(flowTask.getId()).stream().filter(t -> FlowRecordEnum.audit.getCode().equals(t.getHandleStatus()) && statusList.contains(t.getStatus())).collect(Collectors.toList());
        for (UserEntity entity : userName) {
            int num = 0;
            if (properties.getHasAgreeRule()) {
                for (Integer rule : properties.getAgreeRules()) {
                    switch (FlowAgreeRuleEnum.getByCode(rule)) {
                        case initiator:
                            num += entity.getId().equals(creatorUserId) ? 1 : 0;
                            break;
                        case node:
                            List<String> nodeList = taskNodeList.stream().filter(t -> StringUtil.isNotEmpty(t.getNodeNext()) && t.getNodeNext().contains(childNode.getCustom().getNodeId())).map(FlowTaskNodeEntity::getId).collect(Collectors.toList());
                            List<String> list = recordList.stream().filter(t -> nodeList.contains(t.getTaskNodeId())).map(FlowTaskOperatorRecordEntity::getHandleId).collect(Collectors.toList());
                            num += list.contains(entity.getId()) ? 1 : 0;
                            break;
                        case pass:
                            num += recordList.stream().filter(t -> t.getHandleId().equals(entity.getId())).count() > 0 ? 1 : 0;
                            break;
                        default:
                            break;
                    }
                }
            }
            taskOperatoUser.setHandLeId(entity.getId());
            taskOperatoUser.setAutomation(num > 0 && !reject ? "1" : "");
            taskOperatoUser.setSortCode(++sort);
            this.operatorUser(nextList, taskOperatoUser);
        }
    }

    /**
     * 获取审批人
     *
     * @param taskOperator
     * @return
     */
    public List<String> userListAll(TaskOperator taskOperator) {
        List<String> userIdAll = new ArrayList<>();
        ChildNodeList childNode = taskOperator.getChildNode();
        List<FlowTaskNodeEntity> taskNodeList = taskOperator.getTaskNodeList();
        FlowTaskNodeEntity startNode = taskNodeList.stream().filter(t -> FlowNature.NodeStart.equals(t.getNodeType())).findFirst().get();
        ChildNodeList startNodeJson = JsonUtil.getJsonToBean(startNode.getNodePropertyJson(), ChildNodeList.class);
        Properties startProper = startNodeJson.getProperties();
        Boolean errorRule = taskOperator.getErrorRule();
        int pass = 0;
        int notSubmit = 0;
        int node = 0;
        Boolean extraRule = taskOperator.getExtraRule();
        FlowTaskEntity taskEntity = taskOperator.getTaskEntity();
        Properties properties = childNode.getProperties();
        String type = properties.getAssigneeType();
        String createUserId = taskEntity.getCreatorUserId();
        //发起者【发起者主管】
        if (FlowTaskOperatorEnum.LaunchCharge.getCode().equals(type)) {
            UserEntity info = serviceUtil.getUserInfo(createUserId);
            if (info != null) {
                userIdAll.add(getManagerByLevel(info.getManagerId(), properties.getManagerLevel()));
            }
        }
        //发起者【部门主管】
        if (FlowTaskOperatorEnum.DepartmentCharge.getCode().equals(type)) {
            UserEntity userEntity = serviceUtil.getUserInfo(createUserId);
            if (userEntity != null) {
                OrganizeEntity organizeEntity = getManageOrgByLevel(userEntity.getOrganizeId(), properties.getDepartmentLevel());
                if (organizeEntity != null) {
                    userIdAll.add(organizeEntity.getManager());
                }
            }
        }
        //【发起本人】
        if (FlowTaskOperatorEnum.InitiatorMe.getCode().equals(type)) {
            userIdAll.add(createUserId);
        }
        //【环节】
        if (FlowTaskOperatorEnum.Tache.getCode().equals(type)) {
            List<FlowTaskOperatorRecordEntity> operatorUserList = flowTaskOperatorRecordService.getList(taskEntity.getId()).stream().filter(t -> properties.getNodeId().equals(t.getNodeCode()) && FlowRecordEnum.audit.getCode().equals(t.getHandleStatus()) && FlowNodeEnum.Process.getCode().equals(t.getStatus())).collect(Collectors.toList());
            List<String> handleId = operatorUserList.stream().map(FlowTaskOperatorRecordEntity::getHandleId).collect(Collectors.toList());
            userIdAll.addAll(handleId);
        }
        //【变量】
        if (FlowTaskOperatorEnum.Variate.getCode().equals(type)) {
            Map<String, Object> dataAll = JsonUtil.stringToMap(taskEntity.getFlowFormContentJson());
            Object data = dataAll.get(properties.getFormField());
            if (data != null) {
                String formFieldType = properties.getFormFieldType();
                List<String> handleIdAll = new ArrayList<>();
                if ("1".equals(formFieldType)) {
                    try {
                        handleIdAll.addAll(JsonUtil.getJsonToList(String.valueOf(data), String.class));
                    } catch (Exception e) {

                    }
                    if (data instanceof List) {
                        handleIdAll.addAll((List) data);
                    } else {
                        handleIdAll.addAll(Arrays.asList(String.valueOf(data).split(",")));
                    }
                } else {
                    List<String> list = new ArrayList<>();
                    try {
                        list.addAll(JsonUtil.getJsonToList(String.valueOf(data), String.class));
                    } catch (Exception e) {

                    }
                    if (data instanceof List) {
                        list.addAll((List) data);
                    } else {
                        list.addAll(Arrays.asList(String.valueOf(data).split(",")));
                    }
                    List<UserRelationEntity> listByObjectIdAll = serviceUtil.getListByObjectIdAll(list);
                    List<String> userPosition = listByObjectIdAll.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
                    handleIdAll.addAll(userPosition);
                }
                userIdAll.addAll(handleIdAll);
            }
        }
        //【服务】
        if (FlowTaskOperatorEnum.Serve.getCode().equals(type)) {
            String url = properties.getGetUserUrl() + "?" + taskNodeId + "=" + childNode.getTaskNodeId() + "&" + taskId + "=" + childNode.getTaskId();
            String token = UserProvider.getToken();
            JSONObject object = HttpUtil.httpRequest(url, "GET", null, token);
            if (object != null) {
                if (object.get("data") != null) {
                    JSONObject data = object.getJSONObject("data");
                    List<String> handleId = StringUtil.isNotEmpty(data.getString("handleId")) ? Arrays.asList(data.getString("handleId").split(",")) : new ArrayList<>();
                    userIdAll.addAll(handleId);
                }
            }
        }
        //【候选人】
        if (FlowTaskOperatorEnum.FreeApprover.getCode().equals(type)) {
            String nodeId = childNode.getTaskNodeId();
            List<FlowCandidatesEntity> candidatesList = flowCandidatesService.getList(nodeId);
            candidatesList.stream().forEach(t -> {
                List<String> candidates = StringUtil.isNotEmpty(t.getCandidates()) ? JsonUtil.getJsonToList(t.getCandidates(), String.class) : new ArrayList<>();
                userIdAll.addAll(candidates);
            });
        }
        if (!FlowTaskOperatorEnum.FreeApprover.getCode().equals(type)) {
            //【指定用户】
            userIdAll.addAll(properties.getApprovers());
            //【指定岗位】
            List<String> positionList = properties.getApproverPos();
            //【指定角色】
            List<String> roleList = properties.getApproverRole();
            //【指定部门】
            List<String> orgList = properties.getApproverOrg();
            //【指定分组】
            List<String> groupList = properties.getApproverGroup();
            List<String> list = new ArrayList<>();
            list.addAll(positionList);
            list.addAll(roleList);
            list.addAll(orgList);
            list.addAll(groupList);
            List<UserRelationEntity> listByObjectIdAll = serviceUtil.getListByObjectIdAll(list);
            List<String> userPosition = listByObjectIdAll.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
            userIdAll.addAll(userPosition);
        }
        //附加规则
        if (extraRule) {
            this.rule(userIdAll, taskEntity.getId(), properties.getExtraRule());
        }
        //获取最新用户
        List<UserEntity> userList = serviceUtil.getUserName(userIdAll, true);
        //异常规则
        if (errorRule && userList.size() == 0) {
            //异常处理规则
            switch (FlowErrorRuleEnum.getByCode(startProper.getErrorRule())) {
                case administrator:
                    userIdAll.add(user);
                    break;
                case initiator:
                    List<UserEntity> errorRuleUser = serviceUtil.getUserName(startProper.getErrorRuleUser(), true);
                    if (errorRuleUser.size() > 0) {
                        userIdAll.addAll(errorRuleUser.stream().map(UserEntity::getId).collect(Collectors.toList()));
                    } else {
                        userIdAll.add(user);
                    }
                    break;
                case node:
                    String nodeId = childNode.getTaskNodeId();
                    List<FlowCandidatesEntity> candidatesList = flowCandidatesService.getList(nodeId);
                    candidatesList.stream().forEach(t -> {
                        List<String> candidates = StringUtil.isNotEmpty(t.getCandidates()) ? JsonUtil.getJsonToList(t.getCandidates(), String.class) : new ArrayList<>();
                        userIdAll.addAll(candidates);
                    });
                    node++;
                    break;
                case pass:
                    pass++;
                    break;
                case notSubmit:
                    notSubmit++;
                    break;
                default:
                    break;
            }
        }
        taskOperator.setPass(pass);
        taskOperator.setNotSubmit(notSubmit);
        taskOperator.setNode(node);
        return userIdAll;
    }

    /**
     * 递归主管
     *
     * @param managerId 主管id
     * @param level     第几级
     * @return
     */
    public String getManagerByLevel(String managerId, long level) {
        --level;
        if (level == 0) {
            return managerId;
        } else {
            UserEntity userEntity = serviceUtil.getUserInfo(managerId);
            return userEntity != null ? getManagerByLevel(userEntity.getManagerId(), level) : "";
        }
    }

    /**
     * 递归上级部门
     *
     * @param
     * @return
     * @copyright 引迈信息技术有限公司
     * @date 2022/6/29
     */
    private OrganizeEntity getManageOrgByLevel(String organizeId, long level) {
        --level;
        if (level == 0) {
            return serviceUtil.getOrganizeInfo(organizeId);
        } else {
            OrganizeEntity organizeInfo = serviceUtil.getOrganizeInfo(organizeId);
            return organizeInfo != null ? getManageOrgByLevel(organizeInfo.getParentId(), level) : null;
        }
    }

    /**
     * 获取代办用户是否自动通过
     *
     * @param flowTask
     * @throws WorkFlowException
     */
    public void approverPass(FlowTaskEntity flowTask, List<FlowTaskNodeEntity> taskNodeList, FlowModel flowModel, FlowTaskOperatorEntity operator) throws WorkFlowException {
        //查询审批记录
        List<FlowTaskOperatorRecordEntity> recordList = flowTaskOperatorRecordService.getList(flowTask.getId()).stream().filter(t -> FlowNodeEnum.Process.getCode().equals(t.getStatus()) && FlowRecordEnum.audit.getCode().equals(t.getHandleStatus())).collect(Collectors.toList());
        List<String> recordUserList = recordList.stream().map(FlowTaskOperatorRecordEntity::getHandleId).collect(Collectors.toList());
        List<String> taskNodeAll = new ArrayList() {{
            add(operator.getTaskNodeId());
        }};
        List<FlowTaskOperatorEntity> operatorList = flowTaskOperatorService.getList(flowTask.getId()).stream().filter(t -> FlowNodeEnum.Process.getCode().equals(t.getState()) && FlowNature.ProcessCompletion.equals(t.getCompletion()) && recordUserList.contains(t.getHandleId()) && !taskNodeAll.contains(t.getTaskNodeId())).collect(Collectors.toList());
        Map<String, List<FlowTaskOperatorEntity>> operatorMap = operatorList.stream().collect(Collectors.groupingBy(FlowTaskOperatorEntity::getTaskNodeId));
        //获取代办节点
        for (String key : operatorMap.keySet()) {
            FlowTaskNodeEntity taskNode = taskNodeList.stream().filter(t -> t.getId().equals(key)).findFirst().orElse(null);
            if (taskNode != null) {
                List<FlowTaskOperatorEntity> operatorListAll = operatorMap.get(key);
                ChildNodeList childNode = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
                Properties properties = childNode.getProperties();
                Set<FlowTaskOperatorEntity> flowTaskOperatorList = new HashSet<>();
                if (properties.getHasAgreeRule()) {
                    for (Integer rule : properties.getAgreeRules()) {
                        //判断节点是否审批人审批过
                        switch (FlowAgreeRuleEnum.getByCode(rule)) {
                            case initiator:
                                operatorListAll.stream().forEach(t -> {
                                    t.setAutomation(t.getHandleId().equals(flowTask.getCreatorUserId()) ? "1" : "");
                                });
                                break;
                            case node:
                                List<String> nodeList = taskNodeList.stream().filter(t -> StringUtil.isNotEmpty(t.getNodeNext()) && t.getNodeNext().contains(childNode.getCustom().getNodeId())).map(FlowTaskNodeEntity::getId).collect(Collectors.toList());
                                List<String> list = recordList.stream().filter(t -> FlowRecordEnum.audit.getCode().equals(t.getHandleStatus()) && nodeList.contains(t.getTaskNodeId())).map(FlowTaskOperatorRecordEntity::getHandleId).collect(Collectors.toList());
                                operatorListAll.stream().forEach(t -> t.setAutomation(list.contains(t.getHandleId()) ? "1" : ""));
                                break;
                            case pass:
                                operatorListAll.stream().forEach(t -> t.setAutomation("1"));
                                break;
                            default:
                                break;
                        }
                        flowTaskOperatorList.addAll(operatorListAll.stream().filter(t -> StringUtil.isNotEmpty(t.getAutomation())).collect(Collectors.toList()));
                    }
                }
                boolean isApprove = flowTaskOperatorList.size() > 0;
                if (isApprove) {
                    FlowApproveModel approveModel = FlowApproveModel.builder().operatorList(new ArrayList<>(flowTaskOperatorList)).taskNodeList(taskNodeList).flowTask(flowTask).flowModel(flowModel).build();
                    this.approve(approveModel);
                }
            }
        }
    }

    /**
     * 封装审批人
     *
     * @param nextList        所有审批人数据
     * @param taskOperatoUser 对象
     */
    public void operatorUser(List<FlowTaskOperatorEntity> nextList, TaskOperatoUser taskOperatoUser) {
        String handLeId = taskOperatoUser.getHandLeId();
        Date date = taskOperatoUser.getDate();
        ChildNodeList childNode = taskOperatoUser.getChildNode();
        Properties properties = childNode.getProperties();
        Custom custom = childNode.getCustom();
        String type = properties.getAssigneeType();
        FlowTaskOperatorEntity operator = new FlowTaskOperatorEntity();
        operator.setId(RandomUtil.uuId());
        operator.setHandleType(type);
        operator.setHandleId(StringUtil.isEmpty(handLeId) ? user : handLeId);
        operator.setTaskNodeId(childNode.getTaskNodeId());
        operator.setTaskId(childNode.getTaskId());
        operator.setNodeCode(custom.getNodeId());
        operator.setNodeName(properties.getTitle());
        operator.setDescription(JsonUtil.getObjectToString(new ArrayList<>()));
        operator.setCreatorTime(date);
        operator.setCompletion(FlowNature.ProcessCompletion);
        operator.setType(type);
        operator.setState(FlowNodeEnum.Process.getCode());
        operator.setParentId(taskOperatoUser.getId());
        operator.setAutomation(taskOperatoUser.getAutomation());
        operator.setSortCode(taskOperatoUser.getSortCode());
        nextList.add(operator);
    }

    /**
     * 更新经办数据
     *
     * @param operator   当前经办
     * @param handStatus 对象
     */
    public void handleIdStatus(FlowTaskOperatorEntity operator, TaskHandleIdStatus handStatus) {
        int status = handStatus.getStatus();
        ChildNodeList nodeModel = handStatus.getNodeModel();
        FlowModel flowModel = handStatus.getFlowModel();
        Properties properties = nodeModel.getProperties();
        Integer counterSign = properties.getCounterSign();
        operator.setHandleTime(new Date());
        operator.setHandleStatus(status);
        String type = properties.getAssigneeType();
        boolean isApprover = !FlowNature.FixedApprover.equals(counterSign);
        List<String> userIdListAll = new ArrayList<>();
        if (status == 1) {
            boolean hasFreeApprover = StringUtil.isEmpty(flowModel.getFreeApproverUserId());
            if (isApprover) {
                //更新会签都改成完成
                flowTaskOperatorService.update(operator.getTaskNodeId(), userIdListAll, "1");
            } else {
                if (hasFreeApprover) {
                    //更新或签都改成完成
                    flowTaskOperatorService.update(operator.getTaskNodeId(), type);
                }
            }
            operator.setCompletion(FlowNature.AuditCompletion);
            //修改当前审批的定时器
            List<Date> list = JsonUtil.getJsonToList(operator.getDescription(), Date.class);
            DateProperties timer = nodeModel.getTimer();
            if (timer.getTime()) {
                Date date = new Date();
                date = DateUtil.dateAddDays(date, timer.getDay());
                date = DateUtil.dateAddHours(date, timer.getHour());
                date = DateUtil.dateAddMinutes(date, timer.getMinute());
                date = DateUtil.dateAddSeconds(date, timer.getSecond());
                list.add(date);
                operator.setDescription(JsonUtil.getObjectToString(list));
            }
        } else {
            if (isApprover) {
                //更新会签都改成完成
                flowTaskOperatorService.update(operator.getTaskNodeId(), userIdListAll, "-1");
            } else {
                //更新或签都改成完成
                flowTaskOperatorService.update(operator.getTaskNodeId(), type);
            }
            operator.setCompletion(FlowNature.RejectCompletion);
        }
    }

    /**
     * 会签比例
     *
     * @param pass    比例
     * @param total   总数
     * @param passNum 数量
     * @return
     */
    public boolean isCountersign(long pass, double total, double passNum) {
        int scale = (int) (passNum / total * 100);
        return scale >= pass;
    }

    /**
     * 获取通过人数
     *
     * @param operatorList 流程经办数据
     * @return
     */
    public List<FlowTaskOperatorEntity> passNum(List<FlowTaskOperatorEntity> operatorList, Integer completion) {
        //1.先挑选parentId为0,没有加签人的数据
        Set<String> idAll = new HashSet<>();
        List<String> idListAll = operatorList.stream().filter(t -> FlowNature.ParentId.equals(t.getParentId())).map(FlowTaskOperatorEntity::getId).collect(Collectors.toList());
        List<String> childList = operatorList.stream().filter(t -> !FlowNature.ParentId.equals(t.getParentId())).map(FlowTaskOperatorEntity::getParentId).collect(Collectors.toList());
        idListAll.removeAll(childList);
        idAll.addAll(idListAll);
        //2.从加签人中筛选最后审批人数据
        List<String> parentList = operatorList.stream().filter(t -> !FlowNature.ParentId.equals(t.getParentId())).map(FlowTaskOperatorEntity::getId).collect(Collectors.toList());
        parentList.removeAll(childList);
        idAll.addAll(parentList);
        //3.获取最后的审批人数据
        List<FlowTaskOperatorEntity> passListAll = operatorList.stream().filter(t -> idAll.contains(t.getId()) && completion.equals(t.getCompletion())).collect(Collectors.toList());
        return passListAll;
    }

    /**
     * 抄送人
     *
     * @param nodeModel     当前json对象
     * @param circulateList 抄送list
     * @param flowModel     提交数据
     */
    public void circulateList(ChildNodeList nodeModel, List<FlowTaskCirculateEntity> circulateList, FlowModel flowModel) {
        Properties properties = nodeModel.getProperties();
        List<String> userIdAll = new ArrayList<>();
        userIdAll.addAll(properties.getCirculateUser());
        //传阅者【指定分组】
        List<String> groupList = properties.getCirculateGroup();
        //传阅者【指定部门】
        List<String> orgList = properties.getCirculateOrg();
        //传阅者【指定角色】
        List<String> roleList = properties.getCirculateRole();
        //传阅者【指定岗位】
        List<String> posList = properties.getCirculatePosition();
        List<String> userAll = new ArrayList<>();
        userAll.addAll(groupList);
        userAll.addAll(orgList);
        userAll.addAll(roleList);
        userAll.addAll(posList);
        List<UserRelationEntity> listByObjectIdAll = serviceUtil.getListByObjectIdAll(userAll);
        List<String> userPosition = listByObjectIdAll.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
        userIdAll.addAll(userPosition);
        //附加规则
        this.rule(userIdAll, nodeModel.getTaskId(), properties.getExtraCopyRule());
        //指定传阅人
        String[] copyIds = StringUtil.isNotEmpty(flowModel.getCopyIds()) ? flowModel.getCopyIds().split(",") : new String[]{};
        List<String> id = Arrays.asList(copyIds);
        userIdAll.addAll(id);
        //获取最新用户
        List<UserEntity> userList = serviceUtil.getUserName(userIdAll, true);
        for (UserEntity userEntity : userList) {
            FlowTaskCirculateEntity flowTask = new FlowTaskCirculateEntity();
            flowTask.setId(RandomUtil.uuId());
            flowTask.setObjectId(userEntity.getId());
            flowTask.setNodeCode(nodeModel.getCustom().getNodeId());
            flowTask.setNodeName(nodeModel.getProperties().getTitle());
            flowTask.setTaskNodeId(nodeModel.getTaskNodeId());
            flowTask.setTaskId(nodeModel.getTaskId());
            flowTask.setCreatorTime(new Date());
            circulateList.add(flowTask);
        }
    }

    /**
     * 流程任务结束
     *
     * @param flowTask 流程任务
     */
    public boolean endround(FlowTaskEntity flowTask, ChildNodeList childNode, FlowModel flowModel) throws WorkFlowException {
        flowTask.setStatus(FlowTaskStatusEnum.Adopt.getCode());
        flowTask.setCompletion(100);
        flowTask.setEndTime(DateUtil.getNowDate());
        flowTask.setThisStepId(FlowNature.NodeEnd);
        flowTask.setThisStep("结束");
        //结束事件
        FlowTaskOperatorRecordEntity operatorRecord = new FlowTaskOperatorRecordEntity();
        operatorRecord.setTaskId(flowTask.getId());
        operatorRecord.setHandleStatus(flowTask.getStatus());
        UserInfo userInfo = flowModel.getUserInfo();
        operatorRecord.setHandleId(userInfo.getUserId());
        flowTaskService.update(flowTask);
        flowMsgUtil.event(2, childNode, operatorRecord, flowModel);
        FlowEngineEntity engine = flowEngineService.getInfo(flowTask.getFlowId());
        List<FlowTaskNodeEntity> taskNodeList = flowTaskNodeService.getList(flowTask.getId());
        //发送消息
        FlowMsgModel flowMsgModel = new FlowMsgModel();
        flowMsgModel.setEnd(true);
        flowMsgModel.setCirculateList(new ArrayList<>());
        flowMsgModel.setNodeList(taskNodeList);
        flowMsgModel.setOperatorList(new ArrayList<>());
        flowMsgModel.setTaskEntity(flowTask);
        FlowTaskNodeEntity taskNodeEntity = new FlowTaskNodeEntity();
        taskNodeEntity.setNodePropertyJson(JsonUtil.getObjectToString(childNode));
        flowMsgModel.setTaskNodeEntity(taskNodeEntity);
        flowMsgModel.setEngine(engine);
        flowMsgModel.setData(JsonUtil.stringToMap(flowTask.getFlowFormContentJson()));
        flowMsgModel.setFlowModel(flowModel);
        flowMsgUtil.message(flowMsgModel);
        //子流程结束，触发主流程
        boolean isEnd = this.isNext(flowTask, flowModel);
        return isEnd;
    }

    /**
     * 插入数据
     *
     * @param engine    引擎
     * @param flowModel 提交数据
     */
    public Map<String, Object> createData(FlowEngineEntity engine, FlowTaskEntity taskEntity, FlowModel flowModel) throws WorkFlowException {
        Map<String, Object> resultData = flowModel.getFormData();
        UserInfo userInfo = flowModel.getUserInfo();
        Map<String, Object> dataMap = flowModel.getFormData();
        String formId = taskEntity.getProcessId();
        if (FlowNature.CUSTOM.equals(engine.getFormType())) {
            List<TableModel> tableModelList = JsonUtil.getJsonToList(engine.getFlowTables(), TableModel.class);
            //获取属性
            DbLinkEntity link = serviceUtil.getDbLink(engine.getDbLinkId());
            FormDataModel formData = JsonUtil.getJsonToBean(taskEntity.getFlowForm(), FormDataModel.class);
            List<FieLdsModel> list = JsonUtil.getJsonToList(formData.getFields(), FieLdsModel.class);
            Boolean concurrencyLock = formData.getConcurrencyLock();
            Integer primaryKeyPolicy = formData.getPrimaryKeyPolicy();
            TableModel tableModel = tableModelList.stream().filter(t -> "1".equals(t.getTypeId())).findFirst().orElse(null);
            if (concurrencyLock) {
                getVersion(link, tableModel.getTable(), taskEntity.getId(), dataMap, primaryKeyPolicy);
                Integer f_version = dataMap.get("f_version") != null ? Integer.valueOf(String.valueOf(dataMap.get("f_version"))) : 0;
                dataMap.put("f_version", f_version + 1);
            }
            DataModel dataModel = DataModel.builder().dataNewMap(dataMap).fieLdsModelList(list).tableModelList(tableModelList).userInfo(userInfo).mainId(formId).link(link).concurrencyLock(concurrencyLock).primaryKeyPolicy(primaryKeyPolicy).build();
            resultData.putAll(dataMap);
            try {
                resultData.putAll(StringUtil.isNotEmpty(flowModel.getId()) ? flowDataUtil.update(dataModel) : flowDataUtil.create(dataModel));
            } catch (Exception e) {
                throw new WorkFlowException("修改数据异常。");
            }
        } else {
            //系统表单
            String dataAll = JsonUtil.getObjectToString(dataMap);
            if (engine.getType() != 1) {
                String coed = engine.getEnCode();
                try {
                    this.formData(coed, flowModel.getProcessId(), dataAll);
                } catch (Exception e) {
                    throw new WorkFlowException("系统表单反射失败。");
                }
                Integer version = dataMap.get("version") != null ? Integer.valueOf(String.valueOf(dataMap.get("version"))) : 0;
                resultData.put("version", version + 1);
            }
        }
        return resultData;
    }

    /**
     * 更新节点接收时间
     *
     * @param operatorList
     */
    public void taskCreatTime(List<FlowTaskOperatorEntity> operatorList) {
        Map<String, List<FlowTaskOperatorEntity>> operatorMap = operatorList.stream().filter(t -> FlowNature.ParentId.equals(t.getParentId())).collect(Collectors.groupingBy(FlowTaskOperatorEntity::getTaskNodeId));
        for (String key : operatorMap.keySet()) {
            List<FlowTaskOperatorEntity> list = operatorMap.get(key).stream().sorted(Comparator.comparing(FlowTaskOperatorEntity::getCreatorTime)).collect(Collectors.toList());
            Date date = list.size() > 0 ? list.get(0).getCreatorTime() : null;
            if (date != null) {
                FlowTaskNodeEntity taskNodeEntity = new FlowTaskNodeEntity();
                taskNodeEntity.setId(key);
                taskNodeEntity.setCreatorTime(date);
                flowTaskNodeService.update(taskNodeEntity);
            }
        }
    }

    /**
     * 自动审批
     */
    public void approve(FlowApproveModel approveModel) throws WorkFlowException {
        List<FlowTaskOperatorEntity> operatorList = approveModel.getOperatorList();
        Map<String, List<FlowTaskOperatorEntity>> operatorMap = operatorList.stream().collect(Collectors.groupingBy(FlowTaskOperatorEntity::getTaskNodeId));
        List<FlowTaskNodeEntity> taskNodeList = approveModel.getTaskNodeList();
        FlowTaskEntity flowTask = approveModel.getFlowTask();
        FlowModel flowModel = approveModel.getFlowModel();
        List<FlowTaskOperatorEntity> result = new ArrayList<>();
        for (String key : operatorMap.keySet()) {
            FlowTaskNodeEntity taskNode = taskNodeList.stream().filter(t -> t.getId().equals(key)).findFirst().orElse(null);
            if (taskNode != null) {
                result.addAll(this.operator(taskNode, taskNodeList, operatorList, flowModel, flowTask));
            }
        }
        for (FlowTaskOperatorEntity operator : result) {
            FlowTaskNodeEntity flowTaskNode = flowTaskNodeService.getInfo(operator.getTaskNodeId());
            if (FlowNature.ProcessCompletion.equals(flowTaskNode.getCompletion())) {
                UserEntity userEntity = serviceUtil.getUserInfo(operator.getHandleId());
                UserInfo userInfo = flowModel.getUserInfo();
                userInfo.setUserId(userEntity.getId());
                userInfo.setUserAccount(userEntity.getAccount());
                FlowModel parentModel = JsonUtil.getJsonToBean(flowModel, FlowModel.class);
                parentModel.setFreeApproverUserId(null);
                parentModel.setUserId(operator.getHandleId());
                parentModel.setHandleOpinion("自动审批通过");
                parentModel.setUserInfo(userInfo);
                parentModel.setCopyIds(null);
                parentModel.setIsAsync(false);
                flowTaskNewService.audit(flowTask, operator, parentModel);
            }
        }
    }

    /**
     * 验证下一节点和会签比例
     *
     * @return
     */
    public List<FlowTaskOperatorEntity> operator(FlowTaskNodeEntity taskNode, List<FlowTaskNodeEntity> taskNodeList, List<FlowTaskOperatorEntity> operatorList, FlowModel flowModel, FlowTaskEntity flowTask) {
        List<FlowTaskOperatorEntity> result = new ArrayList<>();
        ChildNodeList nodeModel = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
        Properties properties = nodeModel.getProperties();
        boolean fixed = !FlowNature.FixedApprover.equals(properties.getCounterSign());
        List<FlowTaskOperatorEntity> list = operatorList.stream().filter(t -> StringUtil.isNotEmpty(t.getAutomation())).collect(Collectors.toList());
        List<FlowTaskOperatorEntity> operatorListAll = flowTaskOperatorService.getList(taskNode.getTaskId()).stream().filter(t -> t.getTaskNodeId().equals(taskNode.getId()) && FlowNodeEnum.Process.getCode().equals(t.getState())).collect(Collectors.toList());
        boolean isPass = this.pass(taskNodeList, taskNode.getNodeCode(), flowModel, flowTask);
        List<String> operatorId = new ArrayList<>();
        for (FlowTaskOperatorEntity operator : list) {
            operatorId.add(operator.getId());
            operatorListAll.stream().forEach(t -> {
                boolean isCompletion = operatorId.contains(t.getId());
                t.setCompletion(isCompletion ? FlowNature.AuditCompletion : t.getCompletion());
            });
            FlowCountersignModel countersign = new FlowCountersignModel();
            countersign.setTaskNodeId(taskNode.getId());
            countersign.setOperatorList(operatorListAll);
            boolean isCountersign = this.isCountersign(countersign);
            if (isPass || (fixed && !isCountersign)) {
                result.add(operator);
            }
        }
        return result;
    }

    /**
     * 判断是否自动通过
     *
     * @param taskNodeList
     * @param nodeCode
     * @return
     */
    public boolean pass(List<FlowTaskNodeEntity> taskNodeList, String nodeCode, FlowModel flowModel, FlowTaskEntity flowtask) {
        boolean result = false;
        int num = 0;
        List<ChildNodeList> childNodeLists = new ArrayList<>();
        List<FlowTaskNodeEntity> thisList = taskNodeList.stream().filter(t -> t.getNodeCode().equals(nodeCode)).collect(Collectors.toList());
        //当前节点
        for (FlowTaskNodeEntity taskNode : thisList) {
            ChildNodeList taskNodechildNodeList = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
            List<ChildNodeList> childNodeListAll = new ArrayList<>();
            this.candidate(taskNodeList, childNodeListAll, taskNode.getNodeCode(), true);
            for (ChildNodeList childNodeList : childNodeListAll) {
                childNodeLists.add(childNodeList);
                String type = childNodeList.getProperties().getAssigneeType();
                if (taskNodechildNodeList.getCustom().getBranchFlow() || FlowTaskOperatorEnum.FreeApprover.getCode().equals(type)) {
                    num++;
                }
            }
        }
        if (num == 0) {
            result = this.nextUser(childNodeLists, taskNodeList, flowtask, flowModel);
        }
        return result;
    }

    /**
     * 查询下一节点是否有人
     *
     * @return
     */
    public boolean nextUser(List<ChildNodeList> childNodeLists, List<FlowTaskNodeEntity> taskNodeList, FlowTaskEntity flowTask, FlowModel flowModel) {
        int num = 0;
        UserInfo userInfo = flowModel.getUserInfo();
        FlowTaskNodeEntity start = taskNodeList.stream().filter(t -> FlowNature.NodeStart.equals(t.getNodeType())).findFirst().get();
        ChildNodeList startPrope = JsonUtil.getJsonToBean(start.getNodePropertyJson(), ChildNodeList.class);
        Properties properties = startPrope.getProperties();
        List<FlowErrorRuleEnum> list = new ArrayList() {{
            add(FlowErrorRuleEnum.notSubmit);
            add(FlowErrorRuleEnum.node);
        }};
        boolean errorRule = list.contains(FlowErrorRuleEnum.getByCode(properties.getErrorRule()));
        for (ChildNodeList childNodeList : childNodeLists) {
            String nodeId = childNodeList.getCustom().getNodeId();
            TaskOperator taskOperator = new TaskOperator();
            taskOperator.setChildNode(childNodeList);
            taskOperator.setTaskEntity(flowTask);
            taskOperator.setFlowModel(flowModel);
            taskOperator.setTaskNodeList(taskNodeList);
            taskOperator.setUserInfo(userInfo);
            taskOperator.setExtraRule(true);
            List<String> userIdAll = this.userListAll(taskOperator);
            List<UserEntity> userList = serviceUtil.getUserName(userIdAll, true);
            if (!FlowNature.NodeEnd.equals(nodeId)) {
                num += userList.size() > 0 ? 0 : 1;
            }
        }
        boolean result = (num > 0 && errorRule) ? false : true;
        return result;
    }

    /**
     * 获取会签是否通过
     *
     * @param countersign
     * @return
     */
    public boolean isCountersign(FlowCountersignModel countersign) {
        String taskNodeId = countersign.getTaskNodeId();
        List<FlowTaskOperatorEntity> operatorList = countersign.getOperatorList();
        FlowTaskNodeEntity taskNode = flowTaskNodeService.getInfo(taskNodeId);
        ChildNodeList nodeModel = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
        List<String> operatorIdList = new ArrayList<>();
        operatorList.stream().forEach(t -> {
            if (FlowNature.ParentId.equals(t.getParentId())) {
                operatorIdList.add(t.getId());
            }
        });
        this.improperApprover(nodeModel, operatorList, operatorIdList);
        boolean isCountersign = this.fixedJointly(operatorList, nodeModel, countersign);
        return isCountersign;
    }

    /**
     * 查询依次审批比例
     */
    public void improperApprover(ChildNodeList nodeModel, List<FlowTaskOperatorEntity> operatorList, List<String> operatorIdList) {
        Properties properties = nodeModel.getProperties();
        boolean fixed = FlowNature.ImproperApprover.equals(properties.getCounterSign());
        if (fixed) {
            List<FlowOperatorUserEntity> operatorAllIdList = flowOperatorUserService.getTaskList(null, nodeModel.getTaskNodeId());
            for (FlowOperatorUserEntity entity : operatorAllIdList) {
                if (!operatorIdList.contains(entity.getId())) {
                    FlowTaskOperatorEntity taskOperator = new FlowTaskOperatorEntity();
                    taskOperator.setParentId(FlowNature.ParentId);
                    taskOperator.setHandleId(user);
                    taskOperator.setCompletion(FlowNature.ProcessCompletion);
                    operatorList.add(taskOperator);
                }
            }
        }
    }

    /**
     * 过滤依次审批人
     */
    public void improperApproverUser(List<FlowTaskOperatorEntity> operatorListAll, List<FlowTaskNodeEntity> taskNodeList, ChildNodeList nodeModel, FlowTaskOperatorEntity flowOperator) {
        FlowTaskOperatorEntity operatorEntity = new FlowTaskOperatorEntity();
        operatorEntity.setTaskNodeId(nodeModel.getTaskNodeId());
        operatorEntity.setTaskId(nodeModel.getTaskId());
        operatorEntity.setParentId(FlowNature.ParentId);
        Set<Long> operatorIdList = new HashSet<>();
        if (operatorListAll.size() == 0) {
            if (flowOperator != null) {
                List<FlowTaskOperatorEntity> taskOperatorList = flowTaskOperatorService.getList(nodeModel.getTaskId()).stream().filter(t -> FlowNodeEnum.Process.getCode().equals(t.getState())).collect(Collectors.toList());
                this.upOperator(flowOperator, taskOperatorList, operatorIdList);
                List<FlowOperatorUserEntity> taskList = flowOperatorUserService.getTaskList(null, nodeModel.getTaskNodeId());
                List<String> operatorUserId = taskList.stream().filter(t -> operatorIdList.contains(t.getSortCode())).map(FlowOperatorUserEntity::getId).collect(Collectors.toList());
                boolean count = taskOperatorList.stream().filter(t -> operatorUserId.contains(t.getId())).count() > 0;
                if (!count) {
                    operatorListAll.add(operatorEntity);
                }
            }
        }
        Map<String, List<FlowTaskOperatorEntity>> operatorMap = operatorListAll.stream().collect(Collectors.groupingBy(FlowTaskOperatorEntity::getTaskNodeId));
        //下个节点
        for (String key : operatorMap.keySet()) {
            FlowTaskNodeEntity taskNode = taskNodeList.stream().filter(t -> t.getId().equals(key)).findFirst().orElse(null);
            List<FlowTaskOperatorEntity> list = operatorMap.get(key);
            if (taskNode != null) {
                ChildNodeList childNodeList = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
                Properties thisProperties = childNodeList.getProperties();
                boolean thisCounterSign = FlowNature.ImproperApprover.equals(thisProperties.getCounterSign());
                boolean isParentId = list.stream().filter(t -> FlowNature.ParentId.equals(t.getParentId())).count() > 0;
                if (thisCounterSign && isParentId) {
                    List<String> operatorList = flowTaskOperatorService.getList(taskNode.getTaskId()).stream().filter(t -> FlowNature.ParentId.equals(t.getParentId()) && t.getTaskNodeId().equals(taskNode.getId())).map(FlowTaskOperatorEntity::getId).collect(Collectors.toList());
                    List<FlowOperatorUserEntity> taskList = flowOperatorUserService.getTaskList(null, taskNode.getId());
                    List<String> taskUserList = taskList.stream().map(FlowOperatorUserEntity::getId).collect(Collectors.toList());
                    taskUserList.removeAll(operatorList);
                    List<FlowOperatorUserEntity> userList = taskList.stream().filter(t -> taskUserList.contains(t.getId())).sorted(Comparator.comparing(FlowOperatorUserEntity::getSortCode)).collect(Collectors.toList());
                    if (userList.size() > 0) {
                        operatorListAll.removeAll(list);
                        FlowTaskOperatorEntity operator = JsonUtil.getJsonToBean(userList.get(0), FlowTaskOperatorEntity.class);
                        operator.setCreatorTime(new Date());
                        operatorListAll.add(operator);
                    }
                }
            }
        }
        operatorListAll.remove(operatorEntity);
    }

    /**
     * 插入候选人和异常人
     */
    public void candidateList(FlowModel flowModel, List<FlowTaskNodeEntity> taskNodeList, FlowTaskOperatorEntity operator) {
        UserInfo userInfo = flowModel.getUserInfo();
        //新增候选人
        Map<String, List<String>> candidateList = flowModel.getCandidateList() != null ? flowModel.getCandidateList() : new HashMap<>();
        for (String key : candidateList.keySet()) {
            FlowTaskNodeEntity taskNodeEntity = taskNodeList.stream().filter(t -> t.getNodeCode().equals(key)).findFirst().orElse(null);
            if (taskNodeEntity != null) {
                List<String> list = candidateList.get(key);
                FlowCandidatesEntity entity = new FlowCandidatesEntity();
                entity.setHandleId(userInfo.getUserId());
                entity.setTaskId(taskNodeEntity.getTaskId());
                entity.setTaskNodeId(taskNodeEntity.getId());
                entity.setAccount(userInfo.getUserAccount());
                entity.setCandidates(JsonUtil.getObjectToString(list));
                entity.setOperatorId(operator.getId());
                entity.setType(FlowNature.Candidates);
                flowCandidatesService.create(entity);
            }
        }
        //新增异常人
        Map<String, List<String>> candidateErrorList = flowModel.getErrorRuleUserList() != null ? flowModel.getErrorRuleUserList() : new HashMap<>();
        for (String key : candidateErrorList.keySet()) {
            FlowTaskNodeEntity taskNodeEntity = taskNodeList.stream().filter(t -> t.getNodeCode().equals(key)).findFirst().orElse(null);
            if (taskNodeEntity != null) {
                List<String> list = candidateErrorList.get(key);
                FlowCandidatesEntity entity = new FlowCandidatesEntity();
                entity.setHandleId(userInfo.getUserId());
                entity.setTaskId(taskNodeEntity.getTaskId());
                entity.setTaskNodeId(taskNodeEntity.getId());
                entity.setAccount(userInfo.getUserAccount());
                entity.setCandidates(JsonUtil.getObjectToString(list));
                entity.setOperatorId(operator.getId());
                entity.setType(FlowNature.CandidatesError);
                flowCandidatesService.create(entity);
            }
        }
    }

    /**
     * 获取版本号
     *
     * @throws WorkFlowException
     */
    private void getVersion(DbLinkEntity dbLink, String table, String id, Map<String, Object> dataMap, int primaryKeyPolicy) throws WorkFlowException {
        boolean version = true;
        try {
            @Cleanup Connection conn = flowDataUtil.getTableConn(dbLink);
            String pKeyName = flowDataUtil.getKey(conn, table, primaryKeyPolicy);
            String queryVersionSql = "select f_version from " + table + " where " + pKeyName + " = ?";
            PrepareSqlDTO statementDTO = new PrepareSqlDTO(conn, queryVersionSql, id);
            Map<String, Object> map = JdbcUtil.queryOne(statementDTO);
            version = String.valueOf(map.get("f_version")).equals(String.valueOf(dataMap.get("f_version")));
        } catch (Exception e) {
            log.error("查询并发锁异常" + e.getMessage());
        }
        if (!version) {
            throw new WorkFlowException("当前表单原数据已被调整,请重新进入该页面编辑并提交数据");
        }
    }

    /**
     * 获取流程节点
     */
    public void nodeList(List<FlowTaskNodeEntity> taskNodeAllList) {
        Set<FlowTaskNodeEntity> delList = new HashSet<>();
        for (FlowTaskNodeEntity taskNode : taskNodeAllList) {
            ChildNodeList childNode = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
            if (childNode.getCustom().getFlow() && FlowNature.AuditCompletion.equals(taskNode.getCompletion()) && StringUtil.isNotEmpty(childNode.getCustom().getFlowId())) {
                List<String> flowId = Arrays.asList(childNode.getCustom().getFlowId().split(","));
                List<FlowTaskNodeEntity> nodeListAll = taskNodeAllList.stream().filter(t -> flowId.contains(t.getNodeCode())).collect(Collectors.toList());
                List<FlowTaskNodeEntity> add = new ArrayList<>();
                List<FlowTaskNodeEntity> del = new ArrayList<>();
                for (FlowTaskNodeEntity taskNodeEntity : nodeListAll) {
                    boolean branchFlow = JsonUtil.getJsonToList(taskNodeEntity.getCandidates(), String.class).size() > 0;
                    Set<String> rejectNodeList = new HashSet<>();
                    List<String> rejectList = new ArrayList() {{
                        add(taskNodeEntity.getId());
                    }};
                    this.upAll(rejectNodeList, rejectList, taskNodeAllList);
                    List<FlowTaskNodeEntity> rejectNodeListAll = taskNodeAllList.stream().filter(t -> rejectNodeList.contains(t.getId())).collect(Collectors.toList());
                    if (branchFlow) {
                        add.addAll(rejectNodeListAll);
                    } else {
                        del.addAll(rejectNodeListAll);
                    }
                }
                if (add.size() > 0) {
                    del.removeAll(add);
                    delList.addAll(del);
                }
            }
        }
        taskNodeAllList.removeAll(delList);
    }

    /**
     * 附加条件
     */
    public void rule(List<String> userIdAll, String taskId, int rule) {
        List<UserEntity> userList = serviceUtil.getUserName(userIdAll, true);
        List<String> userListAll = userList.stream().map(UserEntity::getId).collect(Collectors.toList());
        Map<String, List<UserRelationEntity>> relationUserList = serviceUtil.getListByUserIdAll(userListAll).stream().collect(Collectors.groupingBy(UserRelationEntity::getObjectId));
        FlowUserEntity flowUser = flowUserService.getTaskInfo(taskId);
        List<String> organize = new ArrayList<>();
        List<String> position = new ArrayList<>();
        List<String> manager = new ArrayList<>();
        List<String> subordinate = new ArrayList<>();
        List<String> department = new ArrayList<>();
        if (flowUser != null) {
            organize.addAll(relationUserList.get(flowUser.getOrganizeId()) != null ? relationUserList.get(flowUser.getOrganizeId()).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList()) : new ArrayList<>());
            position.addAll(relationUserList.get(flowUser.getPositionId()) != null ? relationUserList.get(flowUser.getPositionId()).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList()) : new ArrayList<>());
            manager.add(flowUser.getSuperior());
            subordinate.addAll(StringUtil.isNotEmpty(flowUser.getSubordinate()) ? new ArrayList<>(Arrays.asList(flowUser.getSubordinate().split(","))) : new ArrayList<>());
            List<String> departmentAll = StringUtil.isNotEmpty(flowUser.getDepartment()) ? new ArrayList<>(Arrays.asList(flowUser.getDepartment().split(","))) : new ArrayList<>();
            for (String id : departmentAll) {
                department.addAll(relationUserList.get(id) != null ? relationUserList.get(id).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList()) : new ArrayList<>());
            }
        }
        //附加条件
        switch (FlowExtraRuleEnum.getByCode(rule)) {
            case organize:
                userIdAll.retainAll(organize);
                break;
            case position:
                userIdAll.retainAll(position);
                break;
            case manager:
                userIdAll.retainAll(manager);
                break;
            case subordinate:
                userIdAll.retainAll(subordinate);
                break;
            case department:
                userIdAll.retainAll(department);
                break;
            default:
                break;
        }
    }

    /**
     * 判断审批的初始人
     */
    public void upOperator(FlowTaskOperatorEntity operatorEntity, List<FlowTaskOperatorEntity> operatorList, Set<Long> operatorIdList) {
        List<FlowTaskOperatorEntity> collect = operatorList.stream().filter(t -> t.getId().equals(operatorEntity.getParentId())).collect(Collectors.toList());
        for (FlowTaskOperatorEntity entity : collect) {
            this.upOperator(entity, operatorList, operatorIdList);
        }
        if (FlowNature.ParentId.equals(operatorEntity.getParentId())) {
            operatorIdList.add(operatorEntity.getSortCode() + 1);
        }
    }

}
